如果参数为空,则 SQL 全选,否则返回特定项目 [英] SQL select all if parameter is null else return specific item

查看:27
本文介绍了如果参数为空,则 SQL 全选,否则返回特定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法编写以下脚本,以便在 ProductID 变量为 null 时返回所有产品?并在产品不为空时返回特定产品.到目前为止我所拥有的:

Is there a way to write the following script so that it returns all products if the ProductID variable is null ? And return a specific product when the product it is not null. What I have so far:

DECLARE @productID INT = NULL

SELECT
    ProductID,
    ProductName,
    ProductDesc 
FROM
    product 
WHERE
    ProductID = @productID

推荐答案

用例说明:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID = CASE WHEN @productID IS NULL THEN ProductID ELSE @productID END

或者 IIF() 函数(如果您使用的是 SQL Server 2012):

Or IIF() function if you’re using SQL Server 2012:

SELECT ProductID, ProductName,ProductDesc 
FROM product 
WHERE ProductID =IIF(@productID IS NULL, ProductID, @productID )

这篇关于如果参数为空,则 SQL 全选,否则返回特定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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