SQL Server条件where子句基于声明的变量

时间:2018-01-13 09:59:27

标签: sql-server tsql

是否可以根据声明的变量使用条件where子句?

请注意:我的查询比这复杂得多,我只是用这个例子来简化。

类似的东西:

DECLARE @ITEST INT = 1

SELECT NAME, LNAME, CADDRESS
FROM JEEVEN
WHERE
CASE WHEN @ITEST = 1 THEN
(
    (EVEN_KEY > 5 AND EVEN_KEY < 10)
)
CASE WHEN @TEST = 2 THEN
(
    (EVEN_KEY > 20 AND EVEN_KEY < 30)
) 

1 个答案:

答案 0 :(得分:2)

您正在寻找此

DECLARE @ITEST INT = 1

SELECT NAME, LNAME, CADDRESS
FROM JEEVEN
WHERE (@ITEST = 1 AND EVEN_KEY > 5 AND EVEN_KEY < 10)
   OR (@ITEST = 2 AND EVEN_KEY > 20 AND EVEN_KEY < 30)