2012-05-31 26 views
1

我有10個表中的SQL,並從表中獲得記錄,其中id與UNION ALL匹配;但我的問題,結果發現查詢停止進一步處理;就像c#函數中的return語句一樣#SQL查詢返回,如果結果發現否則繼續查詢,直到結束行

+0

所以你說你不想執行聯合中剩餘的查詢,一旦你已經找到1個結果?建議聯盟不是正確的選擇。 –

+0

是的,我不想執行其餘的查詢! 忘記UNION只是正確的選擇和好辦法做到這一點。 – Ghazni

+0

看起來像「男孩」提供了一些替代品在我的缺席,當然我不知道的方式打破了SQL語句。 –

回答

0

如果你打算繼續使用UNION ALL是不可能的。

爲什麼不一次做出選擇並在每次選擇後檢查,如果您有所需的信息?如果是這樣,結束它,如果沒有,繼續並做另一個選擇。

0
IF (exists(select 1 from table1 where condition)) 
    select col1, col2 from table1 
    where condition 
else if(exists(select 1 from table2 where condition)) 
    select col1, col2 from table2 
    where condition 
else if(exists(select 1 from table3 where condition)) 
    select col1, col2 from table3 
    where condition 
... continue until table10 
1
select ... from T1 where ... 
if @@RowCount = 0 
    select ... from T2 where ... 
if @@RowCount = 0 
    select ... from T3 where ... 

如果你需要對結果做額外的處理,你既可以SELECT INTO臨時表或INSERT/SELECT到表變量。

編輯:基於來自OP的評論,可能我建議:

declare @Table1 as Table (Id Int) 
declare @Table2 as Table (Id Int) 
declare @Table3 as Table (Id Int) 
declare @Result as Table (Id Int, Source VarChar(10)) 

-- Try changing the following line to use different tables and values. 
insert into @Table2 (Id) values (42) 

insert into @Result 
    select Id, 'Table1' from @Table1 where Id = 42 
if @@RowCount = 0 
    insert into @Result 
    select Id, 'Table2' from @Table2 where Id = 42 
if @@RowCount = 0 
    insert into @Result 
    select Id, 'Table3' from @Table3 where Id = 42 

select * from @Result 
+0

不能正常工作;因爲如果第一個選擇結果爲空,那麼它會顯示其他結果,如果第一個表沒有結果,則表示總是先顯示兩個輸出爲空,另一個爲結果表。 – Ghazni