2013-02-13 166 views
4

我有一个简单的查询是这样的:SQL Server中使用CASE WHEN THEN语句

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) 

当我执行查询时出现错误弹出表示:

不正确的语法关键字附近“是”。

任何想法为这家伙工作?

谢谢!

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

+0

什么正在努力实现用'情况when'?您在查询中放置了'null'和'not null'不正确。 – 2013-02-13 08:53:51

+0

如果参数@qualified的值为2我希望得到table2中的所有空行,并且如果它的值为3我想获得table2中的所有非空行 – jr17 2013-02-13 08:57:02

+0

请解释此查询的目的因为它不是一个正确的查询。 – Joshi 2013-02-13 08:57:23

回答

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 
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 
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)[email protected]