如何编写一个有多个case的where子句?

时间:2013-03-28 16:26:30

标签: sql where-clause

我有一个具有可为空参数的存储过程,以下是我的查询

select * 
from table1
where table1.id = isnull(@id, table1.id)

现在有一些特殊的ID我用不同的方式对待它们。我正在添加另一个表table2,如下所示

combid    id
1         abc01
1         abc02
1         abc03
2         hig01
2         hig02

我必须更改查询以满足以下情况

  1. 如果@id为null,则where子句为table1.id = table1.id
  2. 如果@id不为空,则为 2.1如果table2中存在@id,则where子句为table1.id in (select id from table2 where combid in (select combid from table2 where id=@id))
    2.2否则where子句将为table1.id = @id
  3. 我尝试过以下查询,但无效。

    select  * from table1
    where (table1.id=@id and not exists(select * from table2 where id=@id)
    or @id is null
    or table1.id in (select id from table2 where combid in (select combid where id=@id)) and  exists(select * from table2 where id=@id))
    

    如何更改存储过程的查询?

2 个答案:

答案 0 :(得分:1)

SELECT * FROM table1
WHERE
    @id IS NULL
    OR
    (
        @id IS NOT NULL
        AND
        (      
            (
                EXISTS (SELECT * FROM TABLE2 WHERE id = @id)
                AND
                table1.id IN (SELECT id FROM table2 WHERE combid in (SELECT combid FROM table2 WHERE id=@id))
            ) 
            OR
            (
                NOT EXISTS (SELECT * FROM TABLE2 WHERE id = @id)
                AND         
                table1.id = @id
            )
        )
    )

答案 1 :(得分:0)

您可以使用if ... else ...而不是只编写一个SELECT语句,使用 if else 可以更容易阅读。


if(@id is null)
    select * from table1
else if exists (select 1 from table2 where id = @id)
    select * from table1 
    where table1.id in 
                  (select id from table2 where combid in 
                         (select combid from table2 where id=@id)
                  )
else 
   select * from table1 where table1.id=@id