SQL-如果变量不为null,则包含条件

时间:2020-01-23 16:47:54

标签: sql

我正在尝试添加仅在变量可变时要检查的where条件 @schoolId不为null,否则返回所有结果。请 知道不能使用If条件,因为它是一个非常大的查询。 这只是其中的一部分。

Table Name - Students

Id Name   SchoolId
1  John      6
2  Mark      6
3  Alice     12
4  Prince   null

查询

Select * from Students st
where st.SchoolId = Case when @schoolId  is not null then @schoolId else st.SchoolId End

因此,如果@schoolId为null,我想返回所有4行。如果变量为null,我也希望它返回SchoolId为null的结果。当前在上面的查询中,它不会返回第四行

3 个答案:

答案 0 :(得分:1)

只需使用or

where (st.SchoolId = @schoolId or @schoolId is null)

您有两个单独的条件,这会同时检查它们。

答案 1 :(得分:1)

您可以使用布尔逻辑代替case表达式:

where (@schoolId is null) or
      (st.SchoolId = @schoolId);

答案 2 :(得分:0)

检查一下:

declare @schoolId int

If @schoolId is null
Select * 
from dbo.Students st
Else
Select * 
from dbo.Students st
where st.SchoolId = @schoolId