2013-01-03 39 views
0

我想用這個功能在sql存儲過程中編寫where子句。改進where子句

if (@userId=0) 
begin 
    SELECT * from tblUsers 
end 
else 
begin 
    SELECT * from tblUsers 
    WHERE userId= @userId 
end 

當我發送一個id(example:123)存儲過程就應該給我一個具體,當我發送「0」作爲ID,它應該返回整個數據 但是我不想,如果其他人使用。應該有一些我可以改進我的where子句的東西。

例如

SELECT * from tblUsers 
WHERE (userId= @userId OR @userId = 0) and @userId = 123... bla bla 

(或這當然不是)

任何幫助嗎?

+0

爲什麼第二個代碼段不可接受? – shahkalpesh

+0

第二個查詢(但沒有'和@userId ...'位)似乎是你想要的。順便說一下,通常建議您使用NULL來指示沒有值,而不是自己創建標記值 - 這就是它的用途。 –

回答

1

只是建議,如果你傳遞null在@userid比你能做到這樣很容易

SELECT * from tblUsers 
    WHERE userId= Isnull(@userId,userId) 

這避免額外的條件.. .just pass @ useId = null如果沒有數據,或者您可以這樣做

if (@userId=0) 
    select @userId = null 
SELECT * from tblUsers 
    WHERE userId= Isnull(@userId,userId) 
+0

謝謝你。好的解決方案 – Rapunzo

3

可以在where子句中使用的情況下條件:

SELECT 
    * 
from 
    tblUsers 
WHERE 
    userId=(case when @userId=0 then userId else @userId end) 
+0

它也有效,謝謝你的迴應。 – Rapunzo