我尝试执行此查询,其中我有一个 where子句。问题是我需要在where条件下使用运算符IN但我无法弄清楚 我错过了什么。
有人可以帮忙吗?这是我的查询
DECLARE @OP INT = 1
SELECT * FROM Table
WHERE
Table.[status] IN (CASE WHEN @OP = 1 THEN (5,6) ELSE (12) END)
答案 0 :(得分:7)
不需要案例陈述。
DECLARE @OP INT = 1;
SELECT * FROM Table
WHERE (@OP = 1 AND Table.[status] IN (5,6))
OR (@OP !=1 AND Table.[status] IN (12))
答案 1 :(得分:3)
尝试:
DECLARE @OP INT = 1
SELECT * FROM TABLE
WHERE
((@OP = 1 AND TABLE.[status] IN (5,6)) OR (@OP <> 1 AND TABLE.[status] = 12))
答案 2 :(得分:0)
另一种选择:
DECLARE @OP INT = 1
SELECT * FROM Table
WHERE
1 = (CASE WHEN @OP = 1 CASE WHEN Table.[status] IN (5,6) THEN 1 END
ELSE CASE WHEN Table.[status] = 12 THEN 1 END
END)
嵌套的case语句可以帮助查询计划利用case语句短路。如果没有嵌套的情况,你也可以这样做:
DECLARE @OP INT = 1
SELECT * FROM Table
WHERE
1 = (CASE WHEN @OP = 1 AND Table.[status] IN (5,6) THEN 1
WHEN @OP <> 1 AND Table.[status] = 12 THEN 1
END)