多条件组合查询的解决方案

来源:互联网 发布:同城交友app源码 编辑:程序博客网 时间:2024/06/05 03:04

 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

 

 
   

 

 


  

原创粉丝点击