conditional stored procedure with/without passing parameter

后端 未结 3 1827
Happy的楠姐
Happy的楠姐 2020-12-21 12:15

I created a stored procedure which when passed nothing as parameter should return the entire table. But if the studentId is passed, then return her details. Something like t

3条回答
  •  醉话见心
    2020-12-21 12:59

    Shorter way to do that:

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

    You can't chack if value is null using =. For your example you have to replace condition @studentId = null to is null syntax.

    Try to change your code as below:

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

提交回复
热议问题