在where子句中使用case?

时间:2011-10-19 13:31:09

标签: sql-server tsql

  

可能重复:
  TSQL- Using CASE in WHERE clause with a < or = sign

如何在SQL Server存储过程中使用此查询?

@VAR1 VARCHAR(2),
AS

SELECT     
    *
FROM         
    TABLE1
WHERE     
    Colum1 = 1
    CASE WHEN @VAR1 = 'OK' THEN 
           AND Colum2 = @Var1
    ELSE
           AND Colum2 IN ('String1','String2')
    END

现在非常感谢你。

1 个答案:

答案 0 :(得分:2)

正如Martin Smith在评论中已经指出的那样,你不能使用CASE来换掉WHERE条款。

你可以做的是:

SELECT     
    *
FROM         
    TABLE1
WHERE     
    Colum1 = 1
    AND 
    (
        (@VAR1 = 'OK' and Colum2 = @VAR1)
        OR
        (@VAR1 <> 'OK' and Colum2 IN ('String1','String2'))
    )