【问题标题】:How to write a where clause that has multiple cases?如何编写具有多种情况的 where 子句?
【发布时间】: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

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

  1. 如果@id 为空,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

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

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


【解决方案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
            )
        )
    )

【讨论】:

  • 这真的很慢,我必须杀了它。
  • 不太对。我得到了 table1.id 也是空的记录。如果我通过 null,我得到 0 记录。
  • 很抱歉,只有当 table1 为空时,查询才能为传递的 null 返回 0 行。所以要么你没有正确实现或解释它,要么我没有理解这个请求,但是这个查询工作正常。这是 SQL Fiddle 演示:sqlfiddle.com/#!6/e05c0/2 包含所有 3 个案例。你可以检查它是如何工作的。如果您的表中有什么不同,请使用 sql fiddle 提供更好的示例数据和预期结果。
【解决方案2】:

您可以使用 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

【讨论】:

  • 谢谢。但我需要将所有逻辑放在 where 子句中。
  • 我也不能使用这个方法,因为我会将结果插入到临时表中。
  • 为什么必须将所有逻辑都放在 where 子句中?您仍然可以在 IF...ELSE... 中插入临时表...就在每次选择之前,将插入添加到 @temptable...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
相关资源
最近更新 更多