SQL Server使用CASE WHEN THEN语句

时间:2013-02-13 08:50:49

标签: sql sql-server case-when

我有一个这样的示例查询:

select t1.name,t1.bday,t2.address,t2.contactnum
from table1 as t1
left join table2 as t2 on t1.p_id = t2.p_id
where (case when @qualified = '2' then t2.role is null
        case when @qualified = '3' then t2.role is not null` end)

执行查询时会弹出一个错误,指示:

  

关键字'is'附近的语法不正确。

为这些家伙解决任何想法?

谢谢!

此查询的目的是获取表中的空行和非空行,具体取决于参数@qualified上传递的值。

4 个答案:

答案 0 :(得分:5)

试试这个:

select t1.name,t1.bday,t2.address,t2.contactnum
from table1 as t1
left join table2 as t2 on t1.p_id = t2.p_id
where (@qualified = '2' AND t2.role is null) OR (@qualified = '3' AND t2.role is not null)

我相信这种语法代表了您尝试实现的条件表达式。但是,此类WHERE子句可能会导致性能问题。如果发生这种情况,你应该使用:

IF @qualified = '2' THEN
BEGIN
    select t1.name,t1.bday,t2.address,t2.contactnum
    from table1 as t1
    left join table2 as t2 on t1.p_id = t2.p_id
    where t2.role is null
END

IF @qualified = '3' THEN
BEGIN
    select t1.name,t1.bday,t2.address,t2.contactnum
    from table1 as t1
    left join table2 as t2 on t1.p_id = t2.p_id
    where t2.role is not null
END

答案 1 :(得分:0)

试试这个(未经测试)

SELECT t1.name,t1.bday,t2.address,t2.contactnum
FROM table1 as t1
LEFT JOIN table2 AS t2 ON t1.p_id = t2.p_id
WHERE 
    CASE @qualified
        WHEN '2' THEN t2.role is null
        WHEN '3' THEN t2.role is not null 
    END 

答案 2 :(得分:0)

语法不正确: 请查看http://msdn.microsoft.com/en-IN/library/ms181765.aspx

同时发布您的确切要求,以便您可以轻松地建议如何使用CASE。

答案 3 :(得分:0)

请尝试:

select t1.name,t1.bday,t2.address,t2.contactnum
from table1 as t1
left join table2 as t2 on t1.p_id = t2.p_id
where (case when t2.role is null then '2' else '3' end)=@qualified