如果参数为null,则返回空值,否则返回参数的特定值

时间:2018-01-28 09:22:20

标签: sql sql-server tsql

我正在创建一个存储过程,如果输入参数的值为Null,我必须在'Color'列中返回空值,如果输入参数是'Blue',我必须返回“颜色”列,其值为“蓝色”。这是我的sql代码:

Create Proc Reports.GetProductsByColor @Color nvarchar(20)
AS
SET NOCOUNT ON
SET ANSI_NULLS OFF
BEGIN
Select SalesLT.Product.ProductID as ProductID,
       SalesLT.Product.Name as 'Name',
       SalesLT.Product.ListPrice as Price,
       SalesLT.Product.Color as Color,
       SalesLT.Product.Size as Size
From   SalesLT.Product
Where  Color = CASE WHEN @Color is NULL
               THEN NULL
               ELSE @Color
               END
END
GO
Exec Reports.GetProductsByColor 'Blue'
GO
Exec Reports.GetProductsByColor NULL
GO

Exec Reports.GetProductsByColor 'Blue'完美无缺,仅显示“蓝色”值。但是,对于Exec Reports.GetProductsByColor NULL,即使“颜色”列中有50个NULL值,我也不会得到任何结果集。我在这做错了什么?任何反馈将不胜感激。谢谢:D

3 个答案:

答案 0 :(得分:5)

由于null = null返回不起作用的false。使用

Where (@Color is NULL and Color is null)
   or (@color = color)

答案 1 :(得分:0)

试试这个:

where ISNULL(Color,'-') =IsNUll(@Color,'-') 

请注意,以下WHERE子句不是SARG,如果可用,则不会将关联索引与Color列一起使用。

要解决SARG问题,您需要使用@juergen's solution

答案 2 :(得分:0)

Create Proc GetProductsByColor @Color nvarchar(20)
AS
SET NOCOUNT ON
SET ANSI_NULLS OFF
BEGIN
    if(@color is null)
       Select  SalesLT.Product.ProductID as ProductID,
               SalesLT.Product.Name as 'Name',
               SalesLT.Product.ListPrice as Price,
               SalesLT.Product.Color as Color,
               SalesLT.Product.Size as Size
        From   SalesLT.Product
        Where  Color is NULL
    else 
        Select SalesLT.Product.ProductID as ProductID,
               SalesLT.Product.Name as 'Name',
               SalesLT.Product.ListPrice as Price,
               SalesLT.Product.Color as Color,
               SalesLT.Product.Size as Size
        From   SalesLT.Product
        Where  Color = @Color
END
GO
Exec GetProductsByColor 'Blue'
GO
Exec GetProductsByColor NULL
GO
相关问题