0

这就是存储过程的结构:

[dbo].[getSp] (
  @Color varchar(10) = Null,
  @Finish varchar(10) = Null,
  @Height varchar(10) = Null,
  @Type varchar(10) = Null,
  @Trim varchar(10) = Null,
  @Width varchar(10) = Null
)

这是数据在搜索之前的样子。这个数据不完整,但作为一个例子来了解一下。每个组合都会在这里..

Color  |  Finish  |  Height  |   Type    |  Trim  |  Width  |
 Blue  |  Shiny   |   Tall   |  Toaster  | Normal |   3.5   |
(NULL) |  (NULL)  |  (NULL)  |  Toaster  | (NULL) |   3.5   |
(NULL) |  (NULL)  |   Tall   |  Toaster  |  Deco  |    4    |
(NULL) |  Shiny   |   Tall   |  Toaster  |  Deco  |    4    |
 Blue  |  Shiny   |  (NULL)  |  Toaster  |  Deco  |    4    |
(NULL) |  Shiny   |   Tall   |  Toaster  |  Deco  |    4    |
(NULL) |  Satin   |   Tall   |  Toaster  |  Deco  |    4    |
  Red  |  (NULL)  |   Tall   |  Toaster  |  Deco  |    4    |

SELECT 语句将Type作为主要查找字段,因此它看起来像这样:

SELECT * FROM TABLE WHERE Type = @Type And
(

..... Confused about this part, 

)

但基本上,我想运行一个存储过程以仅包含那些组合,这些组合是在仅使用部分参数调用时在表中找到的行,如下所示:

[getSp] 
@Color='Blue',
@Finish='Shiny',
@Type='toaster'

而 sp 最终会返回这个(每个组合)..

1. Blue Shiny Tall Toaster
2. Blue Shiny Toaster
3. Blue Tall Toaster
4. Blue Toaster
5. Tall Toaster
6. Shiny Toaster
7. Shiny Tall Toaster

所以我对如何Where在存储过程中构造语句以仅返回存储过程参数中包含的那些组合的每个组合感到困惑,但剩余的参数(比如Width并且Trim将被排除在结果和搜索之外,将和何时默认通过NULL

我试过这个没有任何运气......

SELECT * FROM TABLE WHERE 
Type = @Type AND
(
COLOR = COALESCE(@Color,COLOR) AND...
... for each other param
)

我试过这个没有任何运气......

SELECT * FROM TABLE WHERE 
Type = @Type AND
(
(Color = @Color OR COALESCE(@Color,COLOR) IS NULL) OR...
... for each other param
)

我已经尝试构建 sql 语句,但也失败了。任何建议都会有所帮助。

4

1 回答 1

0

这应该满足您的需求,如果您提供一个参数,那么它会使用它来过滤,否则它不会:

SELECT *
FROM table_1
WHERE (@Color IS NULL OR Color = @Color)
AND (@Finish IS NULL OR Finish = @Finish)
AND (@Height IS NULL OR Height = @Height)
AND (@Type IS NULL OR Type = @Type)
AND (@Trim IS NULL OR Trim = @Trim)
AND (@Width IS NULL OR Width = @Width)
于 2012-04-18T05:16:27.157 回答