2010-04-05 19 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