SQL Server:检查 WHERE 子句的变量是否为空或 NULL

新手上路,请多包涵

搜索产品列表时, @SearchType 参数是可选的。如果 @SearchType 为空或 NULL 那么它应该返回所有产品并且不使用 WHERE 子句。否则,如果它通过了 Equipment 它将使用它来代替。

 ALTER PROCEDURE [dbo].[psProducts]
    (@SearchType varchar(50))
AS
BEGIN
    SET NOCOUNT ON;

    SELECT
        P.[ProductId],
        P.[ProductName],
        P.[ProductPrice],
        P.[Type]
    FROM [Product] P
    -- if @Searchtype is not null then use the where clause
    WHERE p.[Type] = @SearchType
END

原文由 User970008 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 608
2 个回答

只需使用

如果 @searchType 为 null 表示“返回整个表”,则使用

WHERE p.[Type] = @SearchType OR @SearchType is NULL

如果@searchType 是一个空字符串,则表示“返回整个表”,然后使用

WHERE p.[Type] = @SearchType OR @SearchType = ''

如果 @searchType 为 null 或空字符串表示“返回整个表”,则使用

WHERE p.[Type] = @SearchType OR Coalesce(@SearchType,'') = ''

原文由 Phil 发布,翻译遵循 CC BY-SA 3.0 许可协议

ALTER PROCEDURE [dbo].[psProducts] (@SearchType varchar(50)) AS BEGIN SET NOCOUNT ON;

 SELECT
    P.[ProductId],
    P.[ProductName],
    P.[ProductPrice],
    P.[Type]
FROM [Product] P
-- if @Searchtype is not null then use the where clause
WHERE p.[Type] = @SearchType

结尾

答:

在上述情况下:您可以使用

其中(p.Type 为 null 且 @SearchType 为 null)或(p.Type 不为 null 且 p.Type = @SearchType)

原文由 TDekate 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进