gpt4 book ai didi

SQL 在 WHERE IN 子句中使用 CASE 语句

转载 作者:行者123 更新时间:2023-12-03 12:06:34 25 4
gpt4 key购买 nike

是否可以在 where in 子句中使用 case?
像这样:

 DECLARE @Status VARCHAR(50);
SET @Status='published';

SELECT * FROM Product P
WHERE P.Status IN (CASE WHEN @Status='published' THEN (1,3)
WHEN @Status='standby' THEN (2,5,9,6)
WHEN @Status='deleted' THEN (4,5,8,10)
ELSE (1,3)
END)
此代码给出了错误:',' 附近的语法不正确。

最佳答案

不,您不能使用 casein像这样。但是你可以做

SELECT * FROM Product P    
WHERE @Status='published' and P.Status IN (1,3)
or @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)

顺便说一句,您可以将其减少到
SELECT * FROM Product P    
WHERE @Status='standby' and P.Status IN (2,5,9,6)
or @Status='deleted' and P.Status IN (4,5,8,10)
or P.Status IN (1,3)

or P.Status IN (1,3)还为您提供了 @Status='published' and P.Status IN (1,3) 的所有记录

关于SQL 在 WHERE IN 子句中使用 CASE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19271853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com