日期:2014-05-17  浏览次数:20691 次

在存储过程中的参数的问题


create table #tableTest(id int identity , name varchar(20),age int,)
go
insert into #tableTest
select '小明',23 union all
select '小红',28 union all
select '小军',27
go
select *from #tableTest
go


create proc procTest
@name varchar(20),
@age int,
@IDs varchar(30)
as
begin
select *from #tableTest where 1=1
end

--当我传入@name参数等于 小明,23岁,还有ID在(1,3)的时候
--我怎么可以弄成可选的参数
--比如,name不为空时候
select *from #tableTest where 1=1 and name like '小明'
--如果name参数为空的时候,IDs参数不为空的时候
select *from #tableTest where 1=1 and id in(1,3)
--请问一下,就有参数不为空的时候存储过程中的SQL追加条件,为空的时候就不追加,这样带可选参数的存储过程怎么写,以及怎么调用,请帮小弟写一个实例

------解决方案--------------------
name like '参数值' 和name = '参数值' 是一样的.
如果为空就等于原来值,不为空就等于参数值,我用charindex()函数可以匹配模湖查询.不想匹配模湖查询就改下:
name=case when @name='' then name else @name end

---->如果ID 不为空可是加成这样的喔, id in(ID参数值) , 
我那样写没问题:

create proc procTest
@name varchar(20)='小明',
@IDs varchar(30)='1,3'
as
set nocount on 

select * 
from #tableTest  
where 1=1 
and name=case when @name='' then name else @name end   
and case when len(@IDs)>0 
then charindex(','+cast(id as varchar)+',',','+@IDs+',') else 1 end > 0 
go