当查询条件的个数不定的时候,如何在存储过程中动态生成select语句的where子句?

wangxl430 (卡拉)

查询条件可能的个数不定,例如:
可能是
select * from table1 where a>4 and b<100
也可能是
select * from table1 where a=10 and b<50 and c like 'aaa'+'%'
也可能是
select * from table1 where c like 'bbb'+'%'
很多种情况,唯一可以确定的是条件的最大个数是固定的。
我的想法是将各个条件的参数(如果存在该条件的话)给到存储过程里
然后执行存储过程,存储过程中怎样判断呢?

回复人: Softlee81307(孔腎) ( 三级(初级)) 信誉:100

給一個例子給你  ,你把表名改成你的表就可以了

Create Procedure kp
@k  varchar(300)
as
  Declare  @s  Varchar(1000)
  set @s='Select *  from 表名 Where  '+@k
  exec(@s)
---------------------------------
---------exec kp 'a>4 and b<100'
---------exec kp 'where a=10 and b<50 and c like 'aaa'+'%''

回复人: daijingjie2002(艰苦创业) ( 三级(初级)) 信誉:97

create proc pro
@a integer,
@b integer,
@c varchar(50)
as
declare @ss varchar(8000),
@ii integer
select @ii=0
select @ss='select * from 表 where '
if @a not is null
begin
  select @ss=@ss+' a='+''+@a+''
  select @ii=1
end
if @b not is null
begin
  if @ii=0
  begin
    select @ss=@ss+' b='+''+@b+''
    select @ii=1
  end
  else
  begin
    select @ss=@ss+' and  b='+''+@b+''
  end
end
if @c not is null
begin
  if @ii=0
  begin
    select @ss=@ss+' c like '+''+@c+'%'++''
    select @ii=1
  end
  else
  begin
    select @ss=@ss+' and  c like '+''+@c+'%'+''
  end
end

exec (@ss)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值