2017-05-27 127 views
0

我要寫正確的語法嗎?SQL Server - 什麼是正確的語法?

僞代碼

select * from products 
if @value is not null begin where category = @value end 
+ if @value1 is not null begin where other1 = @value1 end 
+ if @value2 is not null begin where other2 = @value2 end 
+ if @value3 is not null begin where other3 = @value3 end 

我是小白。我不想寫一個動態查詢。如何編寫上述查詢?

+1

這是一個錯誤? 「ifs」中的「@ value」應該是「@ value1」,「@ value2」等嗎? – Mureinik

回答

2

這裏是你如何做到這一點,而無需使用動態SQL

select * 
from products 
where (@value is null or category = @value) 
     and (@value1 is null or other1 = @value1) 
     and (@value2 is null or other2 = @value2) 
     and (@value3 is null or other3 = @value3) 

它是如何工作的?

取這條線@value is null or category = @value

上面的條件檢查@value是否爲null。如果是,則整條線/條件評估爲true。所以我們忽略了那裏或其中的一部分。

同樣適用於所有其他條件。

希望這個清楚!