2010-04-05 46 views
2

如果他们没有从表中返回行,我需要获得虚拟值。 If存在自行工作,但给联盟带来错误。有人可以引导我解决方案或解决方法吗?联合和如果存在 - 不能一起工作 - 请帮助

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' 

回答

9

您可以添加另一个工会如果TEST3是空的,它返回假行:

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

这很有效。谢谢。 – user267277 2010-04-05 18:29:17

0

我相信,如果喜欢,你不能使用。 IF语句是控制控制流,现在是数据选择。将查询更改为

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