我正在尝试添加一个where条件,只有在变量@schoolId不为空时才需要检查,否则将返回所有结果。请注意,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因此,如果@學校if为null,我希望返回所有4行。如果变量为空,我也希望它返回SchoolId为空的结果。当前使用上述查询时,它不会返回第4行
发布于 2020-01-24 00:49:06
您可以使用布尔逻辑而不是case表达式:
where (@schoolId is null) or
      (st.SchoolId = @schoolId);发布于 2020-01-24 00:48:58
只需使用or
where (st.SchoolId = @schoolId or @schoolId is null)您有两个独立的条件,此命令将同时检查这两个条件。
发布于 2020-01-24 02:10:46
看看这个:
declare @schoolId int
If @schoolId is null
Select * 
from dbo.Students st
Else
Select * 
from dbo.Students st
where st.SchoolId = @schoolIdhttps://stackoverflow.com/questions/59883460
复制相似问题