0

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

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,如果@idtable2 中存在,则 where 子句将为table1.id in (select id from table2 where combid in (select combid from table2 where id=@id))
    2.2,否则 where 子句将为table1.id = @id

我尝试了以下查询,但不起作用。

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

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

4

2 回答 2

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
            )
        )
    )
于 2013-03-28T16:52:26.720 回答
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
于 2013-03-28T16:45:30.583 回答