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

存储过程里面如何动态拼接sql语句,通过if语句???
现在有学生表,student,
字段如下,

stuid,stuname,stuage,stu_class_id,stumobile,stubirthday,stuaddress


现在想要拼接一条查询语句的存储过程。。

我想知道如果用户不输入某个查询条件是,存储过程里面该如何判断???

类似c#里面

string strsql = "select * from student where 1=1";
if(stuname!="")
{
 strsql += "and stuname link '%name%'";
}




自己尝试了一下,但还是不会。如下:


use testdb
go
if exists (select name from sysobjects where name='getStuList' and type='p')
drop procedure getStuList
go

create procedure getStuList
 @stuid int,
 @stuName nvarchar(50),
 @stuBirthday datetime  
 AS 
 declare @sql nvarchar(1000)
 set @sql='select s.stuID,s.stuName,s.stuSex,s.stuBirthday,s.stuAddress,s.stu_class_id 
 from Student as s where 1=1'
 if @stuid!=null 
 begin 
set @sql = @sql+'and s.stuid='+@stuid 
 end 
 EXEC(@sql)
go 


感觉“set @sql = @sql+'and s.stuid='+@stuid ”怎么也不会执行,请教一下,,谢谢!!!
------最佳解决方案--------------------
先别exec,先print @sql看看出来什么,然后先别放到存储过程里面,先从sql语句调试
------其他解决方案--------------------
传入空值时也可以直接一句话拼成

select s.stuID,s.stuName,s.stuSex,s.stuBirthday,s.stuAddress,s.stu_class_id 
from Student as s where 1=1 AND ISNULL(@stuid,s.stuid) = s.stuid AND ISNULL(@stuname,s.stuname) = s.stuname

------其他解决方案--------------------
引用:
先别exec,先print @sql看看出来什么,然后先别放到存储过程里面,先从sql语句调试


谢谢!!!
------其他解决方案--------------------
 select s.stuID,s.stuName,s.stuSex,s.stuBirthday,s.stuAddress,s.stu_class_id 
 from Student as s where 1=1 
------其他解决方案--------------------
我不是很想帮你把东西都完完全全写好,不然你就算有进步,恐怕都慢的要命。还是先自己学会调试吧。实在不行再问
------其他解决方案--------------------
好像搞定了。。。


use testdb
go
if exists (select name from sysobjects where name='getStuList' and type='p')
drop procedure getStuList
go

create procedure getStuList
 @stuid int,
 @stuName nvarchar(50),
 @stuBirthday datetime  
 AS 
 declare @sql nvarchar(1000)
 set @sql=' select s.stuID,s.stuName,s.stuSex,s.stuBirthday,s.stuAddress,s.stu_class_id 
 from Student as s where 1=1 '
 if(@stuid is not null)
 begin 
set @sql = @sql+' and s.stuID='+convert(nvarchar,@stuid) + ' '
 end 
 
 if(@stuName is not null)
 begin
set @sql = @sql+' and s.stuName like ''%'+@stuName +'%'''
 end
 print (@sql)
go 

------其他解决方案--------------------