多條件組合查詢的解決方案

 create procedure [dbo].[SearchVacation]
(
  @UserID nvarchar(20),
  @LeaveType nvarchar(10),
  @StartDate nvarchar(10)
)
as
begin
  declare @sql nvarchar(3000);
  declare @where nvarchar(3000);
  declare @IsEmpty bit;--0:非空 1:空

  set @sql=N' select * from Leave ';
  set @where =N' ';
  set @IsEmpty=1;--單個條件初始狀態爲空
--====================================================================
--問題:多條件組合查詢時,條件組合可能會出現多種情況。如三個條件的組合查詢:
--      條件存不存在的組合情況就可能出現2*2*2=8種,如果層層嵌套if else 語句,
--      麻煩,費事,費時,還容易出錯
--解決方案:
--      1.設置一個bool類型變量,指示每個條件是不是爲空。不爲空設值爲0
--      2.判斷下一個條件時,可根據設置的布爾類變量,判斷上一個條件是不是爲空,再來組合條件句。
--      3.空:用where連接該條件 非空:and連接該條件
--要點:使用bool類型變量,指示上一條件是否存在,存在則用and連接,不存在則用where連接
--====================================================================
 if @UserID is not null and @userID <>''
   begin
      set @IsEmpty=0;--設置該條件(@UserID)不爲空
      set @where =@where+ ' where userId='''+@userID+'''';--組合條件1
   end

-----------------------

if @LeaveType is not null and @LeaveType <>''
  begin
     if @IsEmpty=0--判斷以上條件(@UserID)不爲空
        begin 
          set @where =@where+' and LeaveType='+@LeaveType; --@userID不爲空,用and連接該條件@LeaveType
        end
     else  --@userID 爲空
        begin
          set @where= @where +' where LeaveType='+@LeaveType; --目前爲止僅有@LeaveType條件存在,用where直接連接
        end
     set @IsEmpty=0;--設置@LeaveType條件不爲空
  end

---------------------- 
if @StartDate is not null and @StartDate <>''
   begin
      if @IsEmpty=0 --以上條件不爲空
         begin
           set @where =@where +' and convert(char(10),StartDate,120) like ''' + @StartDate+''''; --and 連接本條件
         end
      else --以上條件爲空,僅本條件存在
         begin
           set @where =@where+' where convert(char(10),StartDate,120) like ''' + @StartDate+'''';
         end
   end
--============================
 --以下如果還有其他條件要組合,可如以上方法,進行條件組合
--============================
 set @sql=@sql+@where;
 print @sql
 --exec sp_executesql  @sql;
end

 

 
   

 

 


  

發佈了31 篇原創文章 · 獲贊 3 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章