当前位置: 代码迷 >> Sql Server >> SQL存储过程之变量使用(通过变量给SQL语句添加查询条件),该怎么解决
  详细解决方案

SQL存储过程之变量使用(通过变量给SQL语句添加查询条件),该怎么解决

热度:14   发布时间:2016-04-27 17:37:15.0
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
[email protected],来改变上面的查询条件啊?
//如:if(@name!= " ")
//{
//   select   id,name   from   Addresslist where   1=1   and   [email protected]   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 @[email protected]+ ' name= ' ' '[email protected]+ ' ' ' '
if @sex is not null
set @[email protected]+ ' sex= ' ' '[email protected]+ ' ' ' '
...
set @[email protected]+ ' order by name '
exec (@sql)
go

  相关解决方案