具有异常逻辑的SQL Case语句

时间:2014-10-09 19:09:04

标签: sql sql-server

Table:

Q.ID  Name
1   a
2   b
3   c
2   d

现在,如果我传递值1,则输出应为1 a

如果我传递值3,则输出应为3 c

如果我传递值4,我应该得到全桌

WHERE (@SearchTerm IS NULL OR qs.LongLabel LIKE '%' + @SearchTerm + '%' ESCAPE '\' or oe.ANS LIKE '%' + @SearchTerm + '%' ESCAPE '\')
    AND qs.LangID = @LangId AND 
    (@VarName IS NULL OR QNAME LIKE '%' + @VarName + '%' ) AND
(QuestionnaireID = 
        CASE @QuestionnaireType
            WHEN '4' THEN  @QuestionnaireType In('1','2','3')
            ELSE @QuestionnaireType END)    

QuestionnaireID是列名

2 个答案:

答案 0 :(得分:4)

这更简单:

QuestionnaireID = @QuestionnaireType 
OR  @QuestionnaireType = '4'

另一种方式是:

QuestionnaireID = CASE 
                    WHEN @QuestionnaireType = '4' THEN QuestionnaireID
                    ELSE @QuestionnaireType
                  END

答案 1 :(得分:0)

尝试这样:

DECLARE @QuestionnaireType int =4
SELECT * FROM 
(
select * from tbl
where   
          (  @QuestionnaireType=4 and QuestionnaireType IN (1,2,3,4))
           OR QuestionnaireType=@QuestionnaireType
           )d
           where d.QuestionnaireType!=4

SQL Fiddle