【发布时间】:2013-03-29 05:26:35
【问题描述】:
我有一个可以为空的参数的存储过程,下面是我的查询
select *
from table1
where table1.id = isnull(@id, table1.id)
现在有一些特殊的 id 我会区别对待。我正在添加另一个表 table2,如下所示
combid id
1 abc01
1 abc02
1 abc03
2 hig01
2 hig02
我必须更改查询以满足以下情况
- 如果
@id为空,where 子句将为table1.id = table1.id - 如果
@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
我尝试了以下查询,但不起作用。
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))
如何更改存储过程的查询?
【问题讨论】:
-
是的,你试过什么?
标签: sql where-clause