SQL Server:检查变量是否为空或WHERE子句为NULL [英] SQL Server : check if variable is Empty or NULL for WHERE clause

查看:500
本文介绍了SQL Server:检查变量是否为空或WHERE子句为NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索产品列表时, @SearchType 参数是可选的。如果 @SearchType 为空或 NULL 那么它应返回所有产品而不使用 WHERE 子句。否则,如果它通过设备,那么它将使用它。

When searching for a list of products, the @SearchType parameter is optional. If @SearchType is empty or NULL then it should return all products and not use the WHERE clause. Otherwise, if it passed Equipment it would then use that instead.

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


推荐答案

只需使用

如果@ searchType为null表示'返回整个表'然后使用

If @searchType is null means 'return the whole table' then use

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

如果@searchType是空字符串意味着'返回整个表'然后使用

If @searchType is an empty string means 'return the whole table' then use

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

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

If @searchType is null or an empty string means 'return the whole table' then use

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

这篇关于SQL Server:检查变量是否为空或WHERE子句为NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆