存儲過程里多條件判斷(SQL組合查詢)


我存儲過程里想實現多個傳入參數的判斷,里面有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)
    end
  if (@CosName!= '' and @CosID!='')
    begin
      set @sql=@sql+'and'+'  CosName=  '+cast (@CosName as varchar )
    end
  else 
    if (@CosName!='' and @CosID ='')
      begin
        set @sql=@sql+'where '+'  CosName=  '+cast (@CosName as varchar )
      end
  if @CosCredit!= '' and (@CosID!='' or @CosName!='')
    begin
      set @sql=@sql+' and  CosCredit=  '+cast (@CosCredit as varchar )
    end
  else 
    if @CosCredit!='' and @CosID=''and @CosName=''
      set @sql=@sql+'where CosCredit= '+cast (@CosCredit as varchar )
  exec (@sql)
end
GO

無論是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)
end

 

SELECT * 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 .....


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM