SQL Server多條件查詢的實現
SQL Server多條件查詢我們經常會用到,下面就教您如何使用存儲過程實現SQL Server多條件查詢,希望對您學習SQL Server多條件查詢方面有所幫助。
以前使用的方法是將所有參數進行判斷,然后對不同情況組合對應的sql查詢語句,以實現分頁和查詢,但這種方法只適合查詢條件較少的情況,如果查詢條件過多那就恐怖了,比如四個條件查詢,那就有4*4=16中可能要判斷,可想而知,要用多少代碼,辛苦多少腦細胞來寫完這個判斷語句,呵呵。
直到遇到了多達10個查詢條件的查詢事件,這種方法就徹底被我否決了。帶着這種需求,找到了一種簡便又很清晰的方法,
/*查詢資訊類別列表*/ IF EXISTS (SELECT name FROM sysobjects WHERE name = 'get_list_newscate' AND type = 'P') DROP PROCEDURE get_list_newscate GO create proc get_list_newscate @newscate_pid int, @newscate_depth int, @newscate_language int as select * from [news category] where 1=1 and (@newscate_pid is null or newscate_pid=@newscate_pid) and (@newscate_depth is null or newscate_depth=@newscate_depth) and (@newscate_language is null or newscate_language=@newscate_language) order by newscate_orderid
此存儲過程可以實現SQL Server多條件查詢,可以用於網站高級檢索的功能
查詢條件默認為null
程序中值類型不能為null可以在類型后加一個?這樣就可以null
比如:int i=null 錯誤 int? i=null正確
where 1=1是為了當查詢條件都不需要用到時就查詢全部數據
