日期:2014-05-18  浏览次数:20465 次

====== 关于多"查询参数"存储过程 ======
关于多 "查询参数 "存储过程

比如有一学生表

学号         姓名         年龄         年级
---------------------------------
001           张三         12             5
002           李四         13             6

现在想写一存储过程用于获得学生信息
该存储过程有   @学号,@姓名,@年龄,@年级   4个参数
如参数值不为空就进行匹配

比如:   @学号=NULL,@姓名=李四,@年龄=13,@年级=6
就用相当于(SELECT   *   FROM   学生表   WHERE   姓名=李四   AND   ,年龄=13   AND   年级=6)

像这样的存储过程该怎么写?
(不要用动态组合SQL语句的方法.比如:EXEC   @SQL)


       




------解决方案--------------------
--除了用动态SQL外,还有多种方法:

如:用if else 判断

或用如下SQL,但效率不高:

SELECT *
FROM 学生表
WHERE (@学号 is null or 学号= @学号) AND
(@姓名 is null or 姓名= @姓名) AND
(@年龄 is null or 年龄= @年龄) AND
(@年级 is null or 年级= @年级)
------解决方案--------------------
create proc testsp
(
@学号 varchar(10),
@姓名 nvarchar(50),
@年龄 int,
@年级 int
)
as
set nocount on
select *
from 学生表
where @学号=(case when isnull(@学号, ' ')= ' ' then ' ' else 学号 end)
and @姓名=(case when isnull(@姓名, ' ')= ' ' then ' ' else 姓名 end)
and @年龄=(case when isnull(@年龄,0)= ' ' then 0 else 年龄 end)
and @年级=(case when isnull(@年级,0)= ' ' then 0 else 年级 end)
return
)
------解决方案--------------------
修改一下
create proc testsp
(
@学号 varchar(10),
@姓名 nvarchar(50),
@年龄 int,
@年级 int
)
as
set nocount on
select *
from 学生表
where @学号=(case when isnull(@学号, ' ')= ' ' then ' ' else 学号 end)
and @姓名=(case when isnull(@姓名, ' ')= ' ' then ' ' else 姓名 end)
and @年龄=(case when isnull(@年龄,0)=0 then 0 else 年龄 end)
and @年级=(case when isnull(@年级,0)=0 then 0 else 年级 end)
return

------解决方案--------------------
select *
from 学生表
where isnull(@学号,学号)=学号
and isnull(@姓名,姓名)=姓名
and isnull(@年龄,年龄)=年龄
and isnull(@年级,年级)=年级