SQL Server使用CASE WHEN THEN语句

4

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

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所传递的值。


你使用 case when 是为了实现什么目的?你在查询中错误地放置了 is nullis not null - Mohammad Dehghan
如果参数@qualified的值为2,则我想获取table2中所有空行;如果其值为3,则我想获取table2中所有非空行。 - jr17
请解释一下这个查询的目的,因为它不是一个正确的查询。 - Joshi
在 T-SQL 中,CASE 只能返回一个单一的、原子的值 - 而不是表达式或代码块。 - marc_s
4个回答

6

尝试使用以下操作:

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)=@qualified 

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接