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

 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

 

 
   

 

 


  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值