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 上传递的值获取表中的空行和非空行。

4

4 回答 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
于 2013-02-13T08:53:48.417 回答
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 
于 2013-02-13T08:57:37.770 回答
0

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

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

于 2013-02-13T09:02:26.483 回答
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 
于 2013-02-13T09:11:30.823 回答