带/不带传递参数的条件存储过程

时间:2013-07-08 19:40:56

标签: sql stored-procedures

我创建了一个存储过程,当作为参数传递时,应该返回整个表。但如果studentId通过,则返回她的详细信息。 像这样的东西

create procedure usp_GetStudents @studentId int = null
as
  if (@studentId = null)
    select * from Student
  else
    select * from Student where studentId = @studentId

输出

exec usp_GetStudents -- No records returned though there are records in the table


exec usp_GetStudents @studentId = null  -- No records returned


exec usp_GetStudents @studentId = 256  -- 1 entry returned

只是想知道返回表的所有条目的语法/逻辑是否有任何问题?

谢谢

3 个答案:

答案 0 :(得分:4)

您正尝试使用= comparison operator来测试null。如果您使用ANSI null,则对null的任何比较都是false

如果@studentId 任何值(或null),则以下表达式均为false

@studentId = null  -- false
@studentId > null  -- false
@studentId >= null  -- false
@studentId < null  -- false
@studentId <= null  -- false
@studentId <> null -- false

因此,为了测试null,您必须使用特殊谓词is null,即:

@studentId is null

答案 1 :(得分:2)

更短的方法:

create procedure usp_GetStudents @studentId int = null
as
  select * from Student 
  where studentId = isnull(@studentId,studentId)

使用=,如果value为null,则无法查询。 对于您的示例,您必须将条件@studentId = null替换为is null语法。

尝试更改您的代码,如下所示:

create procedure usp_GetStudents @studentId int = null
as
  if (@studentId is null)
    select * from Student
  else
    select * from Student where studentId = @studentId

答案 2 :(得分:0)

将=更改为is

create procedure usp_GetStudents @studentId int = null
as
  if (@studentId is null)
    select * from Student
  else
    select * from Student where studentId = @studentId
相关问题