【问题标题】:SQL: IF/CASE statement within WHERE clauseSQL:WHERE 子句中的 IF/CASE 语句
【发布时间】:2020-08-10 12:21:36
【问题描述】:

是否可以返回匹配 where 子句第一部分的记录;但是,如果没有找到结果,那么移动到 where 子句的第二部分?

例子:

create table #Fruits (
    Fruit varchar(20),
    Color varchar(20),
    Size varchar(20)
)

insert into #Fruits
values ('Apple', 'Red', 'Medium'),
       ('Pear', 'Green', 'Medium'),
       ('Banana', 'Yellow', 'Medium'),
       ('Grapes', 'Purple', 'Small')

select * from #Fruits
where Fruit in ('Apple', 'Grapes') or Color = 'Green'

这显然会返回 Apple、Grapes 和 Pear。我的目标是只找到存在的苹果和葡萄,否则返回绿色的水果。

我试图参考这个类似的问题:SQL: IF clause within WHERE clause,但在合并 where 时遇到了麻烦。

我也尝试过使用@@rowcount:

select * from #Fruits where Fruit in ('Apple', 'Grapes')
if @@rowcount = 0
select * from #Fruits where Color = 'Green'

但如果第一次选择什么都不返回,它仍然返回一个空表作为结果。

谢谢。

【问题讨论】:

    标签: tsql if-statement ssms where-clause case-statement


    【解决方案1】:

    我们可以使用联合来表达你的逻辑:

    select * from #Fruits where Fruit in ('Apple', 'Grapes')
    union all
    select * from #Fruits where Color = 'Green' and
                                not exists (select 1 from #Fruits
                                            where Fruit in ('Apple', 'Grapes'));
    

    我们也许还可以将逻辑组合到一个查询中:

    select *
    from #Fruits
    where
        Fruit in ('Apple', 'Grapes') or
        (Color = 'Green' and
         not exists (select 1 from #Fruits where Fruit in ('Apple', 'Grapes'));
    

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      • 2016-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多