CASE THEN表达式中的结果表达式中的IN语句

时间:2010-03-02 20:17:19

标签: sql-server tsql sql

是否可以在IN中使用CASE..THEN

WHERE
   record.field =
      CASE
          WHEN @flag = 1 THEN a
          WHEN @flag = 2 THEN IN (b, c)
      END

或者如何改写这种情况?

2 个答案:

答案 0 :(得分:6)

对不起,没有:

WHERE
    (@flag = 1 AND record.field = a)
    OR
    (@flag = 2 AND record.field IN (b, c))

答案 1 :(得分:4)

尝试:

WHERE (@flag = 1 AND record.field = a )
    OR (@flag = 2 AND record.field IN (b, c))

尝试加入值并使用索引可能会更好:

DECLARE @Table (ValueOf  int)
INSERT INTO @Table ((ValueOf)
    SELECT a WHERE @flag = 1
    UNION SELECT b WHERE @flag = 2
    UNION SELECT c WHERE @flag = 2

SELECT
    ....
    FROM ...           x
    INNER JOIN @Table  t ON x...=t.ValueOf