我有一个像这样的示例查询:
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)
当我执行查询时,会弹出错误,指示:
Incorrect syntax near the keyword 'is'.
有什么办法可以解决这些人的问题吗?
谢谢!
此查询的目的是根据参数 @qualified 传递的值获取表中的空行和非空行。
最佳答案
试试这个:
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
关于SQL Server 使用 CASE WHEN THEN 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14849636/