SQL存储过程之变量使用(通过变量给SQL语句添加查询条件)
CREATE PROCEDURE treeforsearch (@current varchar(20),@name varchar(20),@sex varchar(20),@tel varchar(20)) as
.....
select id,name from Addresslist where 1=1 order by name
//这里如何通过变量@name等的值是否是为空,来改变上面的查询条件啊?
//如:if(@name!= " ")
//{
// select id,name from Addresslist where 1=1 and name=@name order by name //变成这样的语句
//}
GO
------解决方案--------------------CREATE PROCEDURE treeforsearch (@current varchar(20),@name varchar(20),@sex varchar(20),@tel varchar(20)) as
declare @sql varchar(8000)
set @sql= 'select id,name from Addresslist where 1=1 '
if @name is not null
set @sql=@sql+ ' name= ' ' '+@name+ ' ' ' '
if @sex is not null
set @sql=@sql+ ' sex= ' ' '+@sex+ ' ' ' '
...
set @sql=@sql+ ' order by name '
exec (@sql)
go