57

sql-server – 如果参数为null,则SQL select all all返回特定项

 5 years ago
source link: https://codeday.me/bug/20190112/508961.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

有没有办法编写以下脚本,以便在ProductID变量为null时返回所有产品?并在产品不为空时返回特定产品.

到目前为止我所拥有的:

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:

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

翻译自:https://stackoverflow.com/questions/19357990/sql-select-all-if-parameter-is-null-else-return-specific-item


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK