2011-09-23 66 views
5

我們有兩個表具有相同的結構和基於一個變量我想選擇哪個表選擇不必在我的程序中寫2個查詢。我可以寫一個查詢有一個條件表選擇

這可能嗎?

我試圖

declare @table int 
set @table = 1 

Select orderID, Quantity 
from case when @table = 1 then tblOrders else tblSubscriptionOrders end 
where filled = 0 

但沒有奏效

回答

6

您將需要使用動態SQL這個(假設你想將它擴展到不止2表),這會工作,但是不理想的,因爲SQL不會爲其生成統計信息,並且在優化查詢時有更難的時間。

declare @table sysname 
declare @SQL varchar(1000) 

set @table = 'MyTable' 
SET @SQL='SELECT orderID, Quantity FROM ' + QUOTENAME(@table) + ' WHERE filled=0' 

exec sp_executesql @SQL 

,或者在一個存儲過程:

CREATE PROCEDURE p_ConditionalSelect @table sysname 
as 

declare @SQL varchar(1000) 

set @table = 'MyTable' 
SET @SQL='SELECT orderID, Quantity FROM ' + QUOTENAME(@table) + ' WHERE filled=0' 

exec sp_executesql @SQL 
+0

+1。這很可能會超過我工會的「解決方案」。 –

+0

我試圖避免爲一次執行寫一個sp,儘管這似乎是我不得不做的解決方案,因爲最終結果比我提出的簡單示例更復雜。 – Chad

3

一種選擇是使用動態SQL,但如果性能是不是立竿見影的問題,更簡單的是剛剛UNION表,並添加一個虛擬[table]列可供選擇。

SELECT orderID, Quantity 
FROM (
    SELECT [table] = 1, orderID, Quantity 
    FROM tblOrders 
    UNION ALL 
    SELECT [table] = 2, orderID, Quantity 
    FROM tblSubscriptionOrders 
) t 
WHERE t.Table = @table 
4

如果它只是兩個表,你可以這樣做:

Declare @table = 1 

SELECT * 
FROM Table1 
WHERE <stuff> 
AND @Table = 1 

UNION ALL 

SELECT * 
FROM Table2 
WHERE <stuff> 
AND @Table = 2 

@table的過濾器將導致僅兩個半顯示的數據之一。

+0

+1未經測試,但我認爲這將是最快的解決方案。 –

2

你可以試試這個

declare @table int 
set @table = 1 

Select orderID, Quantity 
From tblOrders 
Where @table = 1 
And filled = 0 

UNION ALL 

Select orderID, Quantity 
From tblSubscriptionOrders 
Where @table = 2 
And filled = 0 

或本:

declare @table int 
set @table = 1 

if @table = 1 
    Select orderID, Quantity 
    From tblOrders 
    Where filled = 0 
else if @table = 2 
    Select orderID, Quantity 
    From tblSubscriptionOrders 
    Where filled = 0 
相關問題