如何在运营商中使用案例

时间:2015-01-20 11:12:41

标签: sql-server sql-server-2008 tsql

具有以下查询:

declare @case int =  1

SELECT a.column1,b.column2
FROM tbl1 a
INNER JOIN tbl2 b on a.id = b.id and a.category in(1,2,3,4,5)

需要@case = 1类别必须在(1,2,3,4,5),当@case = 2时必须是(1,2,4,5)。 像这样:

 SELECT a.column1,b.column2
 FROM tbl1 a
 INNER JOIN tbl2 b on a.id = b.id and (CASE WHEN @case = 1 THEN a.category in(1,2,3,4,5) WHEN @case = 2 THEN (1,2,4,5) ELSE '')

怎么做?

2 个答案:

答案 0 :(得分:2)

SELECT a.column1,b.column2
FROM tbl1 a
INNER JOIN tbl2 b on a.id = b.id 
                 and 
                 (
                     (@case = 1 and a.category in (1,2,3,4,5)) OR
                     (@case = 2 and a.category in (1,2,4,5))
                 ) 

我添加了括号以便于阅读。并非所有这些都是必要的。

答案 1 :(得分:0)

另一个答案是更好的,但如果你碰巧想要用案例做,你可以像

那样做
SELECT a.column1,b.column2
FROM tbl1 a
INNER JOIN tbl2 b on a.id = b.id and 
    (    CASE WHEN @case = 1 and a.category in(1,2,3,4,5) THEN 1
              WHEN @case = 2 and a.category in(1,2,3,4) THEN 1 
              ELSE 0
         END
    ) = 1