2013-05-21 166 views
2

是否可以將值傳遞給存儲過程以告訴它是否將OR語句附加到SQL SELECT語句?SQL語句中的IF語句WHERE子句

我已經試過像這樣,但它是無效的:的

SELECT xyzName 
FROM xyz_fields 
WHERE (xyzType = 'this') UNION ALL 
(if @status=1 OR (xyzType = 'that')) UNION ALL 
(if @status2=1 OR (xyzType = 'somethingelse')) 

有點像在SQL建立WHERE子句,而不是從應用程序再次擊中DB?

+0

嘗試使用case語句。請發佈你的數據和你需要什麼輸出.. –

+0

你必須更具體...你的查詢沒有意義,問題也混亂... – Nathan

回答

2

您可以使用動態SQL來做到這一點。

declare @SqlQuery varchar(100) 

Set @SqlQuery = ' SELECT xyzName FROM xyz_fields WHERE xyzType = ''this'' ' 

if(@status=1) 
Set @SqlQuery = @SqlQuery + ' OR xyzType = ''that'' ' 

if(@status2=1) 
Set @SqlQuery = @SqlQuery + ' OR xyzType = ''somethingelse''' 

exec(@SqlQuery) 

查詢中的單個qoute通過爲另一個qoute加前綴而被轉義。 所以在查詢

WHERE xyzType = 'this' 

應該

WHERE xyzType = ''this'' 
+0

似乎是這樣可能是一個好方法,如果正確,我會放棄並標記爲答案。努力+1,謝謝! – Apqu

+0

更新:這似乎工作得很好,非常感謝發佈此解決方案。 – Apqu

+0

'很高興我能幫到' –

4

我想你的意思是這樣的:

SELECT xyzName 
FROM xyz_fields 
WHERE (xyzType = 'this') 
OR (@status=1 AND (xyzType = 'that')) 
OR (@status2=1 AND (xyzType = 'somethingelse')) 

的第二行where子句僅傳送成功時@status等於1和xyzType等於'那個'。

1
SELECT xyzName 
FROM xyz_fields 
WHERE (xyzType = 'this') 
OR ((xyzType = 'that') AND @status = 1) 
OR ((xyzType = 'somethingelse') AND @status2 = 1) 

@status = 1((xyzType = 'that') AND @status = 1)回報(xyzType = 'that'), 但當@status = 0((xyzType = 'that') AND @status = 1)回報false並不會影響您的查詢。