多条件组合查询的解决方案
来源:互联网 发布:同城交友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
- 多条件组合查询的解决方案
- 多条件组合查询
- 多条件 多可能性 查询 组合有16种以上可能性的解决方案
- Linq 的多条件组合查询
- 多条件查询解决方案
- mybatis多条件的模糊查询解决方案
- JDBC多条件组合查询
- 多条件组合的查询列表页缓存
- hibernate实现多条件组合的模糊查询
- java操作es的多条件组合精确查询BoolQuery
- 多条件组合查询SQL优化一则
- asp中的多条件组合查询实现
- linq to sql 多条件组合查询
- Linq 多条件查询组合问题
- C# MongoDB 多条件动态组合查询
- 多条件组合查询,sql语句连接
- 组合条件查询
- java组合条件查询
- Jboss as 基本设置
- flex知识点6
- 数模转换器静态特性参数
- PKU1631Bridging signals(最长不降子序列)
- 图片 二进制 存入 mysql
- 多条件组合查询的解决方案
- JavaScript读取servlet发出xml信息
- POJ 1700 令人崩溃的边界
- Delphi ActiveX Form的使用实例
- 最好解决方案
- php程序提速原理分析
- JAVA6,请使用字符串加操作。
- 【我所認知的BIOS】—>IDE detect
- CSDN正在从一个学习型社区向娱乐型社区蜕变