SQL Server 使用 CASE WHEN THEN 语句

标签 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)

当我执行查询时,会弹出错误,指示:

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/

相关文章:

sql - 如何在oracle中使用带有if条件的select?

mysql - 相似字符串上的 2 个表的内连接

mysql - 从 MySQL 数据库中搜索 LongBlob 列中的文本

mysql - 使用重复项选择具有最新时间戳MySQL的行

sql-server - VB.NET:SQLite 到 SQL Server

sql server 'in' 或 'or' - 最快

asp.net - SubmitChanges() 上的 LINQ to Entities 超时

sql - 不同于排列的 PostgreSQL 组合

mysql - Django ORM 连接表上的等效 SQL 查询

r - 根据日期之间的等级逐行选择值