2015-03-02 60 views
0

我想編寫一個查詢(微軟SQL SERVER)的模樣:TSQL查詢案例statment

select productid from T1 
union 
select productid from T2 
union 
select ProductID from T3 

的問題是,我想是該聯盟的一個將取決於一個值(允許說@x) 所以,我寫這篇文章的查詢:

select case when @x=1 then productid end 
from T1 
union 
select productid from T2 
union 
select ProductID from T3 

,但它仍然掃描所有T1。

我知道,「案例」表掃描,即使其不匹配的情況:當從T1 1 = 2那麼的productid結束時,我怎麼能寫立足於價值現在,如果執行或查詢 選擇的情況下不是?? 喜歡的東西://的情況下,X = 1,那麼從T1端選擇的productid .... *我需要找到一種方法,而不動態SQL 感謝

+2

在第一個聯合項中使用WHERE子句,例如:'select productid from t1 where @ x = 1 union ...' – 2015-03-02 22:35:49

+0

我不能,因爲@x是獨立的,它不是t1的一部分。我也試過:從t1中選擇productid存在(@ x = 1),但即使在@x!= 1時仍然會掃描所有t1。 – 2015-03-02 22:48:47

+0

然後解釋你實際上想要做什麼,因爲我已經成功地使用了這種技術,並且高效地使用了近三十年。 – 2015-03-02 22:54:07

回答

0

使用本:

Declare @SQL nvarchar(max) 

Set @SQL = N' select productid From T1 ' 
Set @SQl = @SQL + N' UNION select productid From T2' 
if(@x=1) 
Set @SQl = @SQL + N' UNION select productid From T3' 

exec (@SQL) 
0

非常感謝你爲你的幫助, 我設法做它作爲彼得建議,與where子句。查詢樣子

select productid from t1 union select productid from t2 
union select productid from t3 inner join t4 on t3.id=t4.t3id where [email protected] 

雖然我並不想用T4表(因爲@x是佔所有T3之一) 謝謝大家。