當某個參數不傳入值時,查詢語句中where後面不加相應條件處理

假設,存儲過程的兩個參數爲 @p1,@p2

那麼依具存儲過程中的寫法,也有不同的寫法.

SQL code
--1,若是採用動態語句 declare @sql varchar(1000) set @sql='select * from tb where 1=1 ' if @p1 is not null set @sql=@sql + ' and field1=' + @p1 if @p2 is not null set @sql=@sql + ' and field2=' + @p2 --2,若是採用的非動態語句 select * from tb where field1=case when @p1 is null then field1 else @p1 end and field2=case when @p2 is null then field2 else @p2 end 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章