本文介紹了如何在存儲過程中動態添加到 TSQL Where 子句的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
如何給TSQL Where子句動態添加條件?
我試圖避免在兩個完整的 Select 語句之間進行選擇.下面的代碼非常相似,但沒有我的實際代碼那么復雜.
How to dynamically add conditions to the TSQL Where clause?
I'm trying to avoid selecting between two complete Select statements. The following is very similar, but less complicated, than my actual code.
SELECT COUNT(*)
FROM MyTable
WHERE ShipDate >= @FirstDayOfMonth
AND ShipDate < @LastDayOfMonth
AND OrderType = 1
AND NOT OrderCode LIKE '%3'
AND NOT OrderCode LIKE '%4';
我希望能夠根據存儲過程參數的值添加或刪除最后兩個條件.
即:如果 @ExcludePhoneOrders = False ,請不要使用最后兩個 Where 子句條件.
I would like to be able to add or remove the last two conditions depending on the value of a stored procedure parameter.
i.e.: if @ExcludePhoneOrders = False , don't use the last two Where clause conditions.
推薦答案
我不確定你是想包含還是排除,但這里有一個小插曲.
I'm not sure if you meant to include or exclude, but here is a stab at it.
SELECT COUNT(*)
FROM MyTable
WHERE ShipDate >= @FirstDayOfMonth
AND ShipDate < @LastDayOfMonth
AND OrderType = 1
AND (@ExcludePhoneOrders = False OR (NOT OrderCode LIKE '%3' AND NOT OrderCode LIKE '%4'));
這篇關于如何在存儲過程中動態添加到 TSQL Where 子句的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!