存储过程使用默认的NULL参数来返回立方结果

时间:2012-04-18 04:10:31

标签: sql sql-server sql-server-2008

这就是存储过程的结构:

[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语句以返回仅包含在存储过程参数中的那些组合,但剩下的参数(如WidthTrim将被排除在搜索结果之外,默认情况下会以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语句,但也失败了......任何建议都会有所帮助。

1 个答案:

答案 0 :(得分: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)