儲存過程裡多條件判斷 SQL組合查詢

2022-01-17 14:51:24 字數 2718 閱讀 1544

我儲存過程裡想實現多個傳入引數的判斷,裡面有7個傳入引數條件.

create procedure sp_tbwastesource_search

(@sd   datetime,           //開始日期

@ed   datetime,           //結束日期

@con1 varchar(50),        

@con2 varchar(30),        

@con3 varchar(5),        

@con4  varchar(10),       

@con5 varchar(4)         )as

declare @sql varchar(1000)

begin

set @sql='select * from table '

if  @sd!='' and @ed!=''

begin

set @sql=@sql+' where cosid= '+cast(@cosid as varchar)

endif (@cosname!= '' and @cosid!='')

begin

set @sql=@sql+'and'+'  cosname=  '+cast (@cosname as varchar )

endelse 

if (@cosname!='' and @cosid ='')

begin

set @sql=@sql+'where '+'  cosname=  '+cast (@cosname as varchar )

endif @coscredit!= '' and (@cosid!='' or @cosname!='')

begin

set @sql=@sql+' and  coscredit=  '+cast (@coscredit as varchar )

endelse 

if @coscredit!='' and @cosid=''and @cosname=''

set @sql=@sql+'where coscredit= '+cast (@coscredit as varchar )

exec (@sql)

endgo

無論是ado.net還是儲存過程的組合查詢的sql語句編寫方式:select * from temp where (@serverid='' or serverid=@serverid) and (@sname='' or sname=@sname)

sqlparameter param=new sqlparameter("@serverid",serverid==-1?string.empty:serverid.tostring());//這裡的serverid傳遞過來是int型別,如果為-1,那麼查詢全部,傳遞空串即可,否則傳遞serverid,資料庫會自動將@serverid的值轉換為int

sqlparameter param=new sqlparameter("@sname",sname); //字串直接傳引數即可,因為可以為空串string.empty

以下為參考:

create procedure sp_tbwastesource_search

(@sd datetime=null, //開始日期

@ed datetime=null, //結束日期

@con1 varchar(50),

@con2 varchar(30),

@con3 varchar(5),

@con4 varchar(10),

@con5 varchar(4)

)as

begin

select * from tb

where (@sd is null or date>@sd) and (@ed is null or date<@ed)

endselect * from table_name

where ((@sd is null and @ed is null) or (sd >= @sd and ed <= @ed)) --sd和ed都是空時,此條件總為true,否則相當於sd >= @sd and ed <= @ed

and (@con1 is null or con1 = @con1) --如果@con1不傳值,則此行條件總為true;如果傳值,則此行為and con1=@con1

and (@con2 is null or con2 = @con2) --同con1

and (@con3 is null or con3 = @con3) --同con1

and (@con4 is null or con4 = @con4) --同con1

and (@con5 is null or con5 = @con5) --同con1

select * from table

where 1=1

and sd>= case when @sd is not null when @sd else sd end

and ed<= case when @ed is not null when @ed else ed end

and cosid= case when @cosid is not null when @cosid else cosid end

and cosname= case when @cosname is not null when @cosname else cosname end

and .....

儲存過程裡多條件判斷 SQL組合查詢

我儲存過程裡想實現多個傳入引數的判斷,裡面有7個傳入引數條件.create procedure sp tbwastesource search sd datetime,開始日期 ed datetime,結束日期 con1 varchar 50 con2 varchar 30 con3 varchar...

多條件儲存過程 (條件拼接SQL語句)

alter proc sp pagedbyconditions countrycode nvarchar 20 國家編號 cid int,城市的id pageindex int 1,當前要顯示的頁碼 pagesize int 3,每頁要顯示的資料條數 頁大小 totalpages intout 總頁...

sql中使用if多條件判斷

1 以一表為例 bill 單據表 id billno status amount create date 1 gr0001 gr 155 2009 09 09 2 do0001 do 150 2009 09 09 2 so0001 so 153 2009 09 09 說明 status gr表示 進...