【问题标题】:Union and If Exists - not working together - Please help工会和如果存在 - 不一起工作 - 请帮助
【发布时间】:2011-02-04 12:36:14
【问题描述】:

如果它们没有从表中返回行,我需要获取虚拟值。 If exists 可以自行工作,但会导致 Union 错误。有人可以指导我提供解决方案或解决方法吗?

create table test1 (col1 varchar(10))    
create table test2 (col1 varchar(10))    
create table test3 (col1 varchar(10))


insert test1 values ('test1-row1')    
insert test1 values ('test1-row2')    
insert test2 values ('test2-row1')    
insert test2 values ('test2-row2')

select col1 from test1    
union    
select col1 from test2    
union    
if exists (select * from test3)    
    select col1 from test3    
else    
    select 'dummy'

【问题讨论】:

    标签: sql-server union exists if-statement


    【解决方案1】:

    如果 test3 为空,您可以添加另一个返回虚拟行的联合:

    select col1 from test1    
    union    
    select col1 from test2    
    union    
    select col1 from test3    
    union
    select 'dummy' where not exists (select * from test3)
    

    【讨论】:

      【解决方案2】:

      我相信你不能像那样使用 if 。 IF 语句是控制控制流,现在是数据选择。将查询更改为

      IF exists (select * from test3)
      BEGIN
      --query all three
      END
      ELSE
      BEGIN
      --query just two
      END
      

      【讨论】:

        猜你喜欢
        • 2021-11-09
        • 1970-01-01
        • 2016-01-31
        • 2018-10-21
        • 2011-06-28
        • 2023-03-31
        • 1970-01-01
        • 2021-07-02
        • 1970-01-01
        相关资源
        最近更新 更多