关于参数可能为空的存储过程的问题

thisme2401 2005-04-01 03:10:27
如果要为这样的一个查询编写一个存储过程,查询的条件为四个参数,这四个参数可能是空值(相当于用户没有选择这个条件),查询的条件应是传入的条件的“与”的关系,这样如何来实现呢?

如第一个为姓名,第二个为年龄,第三个为性别,第四个为班级,可能只传入姓名和性别这两个参数,条件为“与”的关系,如何来实现这个存储过程呢?

我曾想用判断是否为空来生成一个条件的表达式, 如
declare @condition varchar(255)

这样生成一个条件的表达式,@condition='name=' +@para1, 但下面的语句就检查不过去了。
Select name from student where @condition

谢谢!
...全文
79 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 元老 2005-04-01
  • 打赏
  • 举报
回复
create proc p_qry
@姓名 varchar(100)=null,
@年龄 int=null,
@性别 char(1)=null,
@班级 varchar(100)
as
set nocount on
declare @s nvarchar(4000)
select @s='Select name from student where 1=1'
+case when @姓名>'' then ' and 姓名=@姓名' else '' end
+case when @年龄 is not null then ' and 年龄=@年龄' else '' end
+case when @性别>'' then ' and 性别=@性别' else '' end
+case when @班级>'' then ' and 班级=@班级' else '' end
exec sp_executesql @s,
N'@姓名 varchar(100)=null,
@年龄 int=null,
@性别 char(1)=null,
@班级 varchar(100)'
,@姓名,@年龄,@性别,@班级

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧