0

I am trying to add a where condition to be checked only if variable @schoolId is not null otherwise return all results. Please know that If condition cannot be used because it is a very large query. This is just a part of it.

Table Name - Students

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

Query

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

So if @schoolId is null, I want to return all 4 rows. I want it to return results where SchoolId is null too if variable is null. Currently with above query it does not return 4th row

3 Answers 3

1

You can use Boolean logic instead of case expression :

where (@schoolId is null) or
      (st.SchoolId = @schoolId);
Sign up to request clarification or add additional context in comments.

3 Comments

This won't work because it will only return null value if schoolId is not provided
. . . No, it will return all rows when @schoolId has no value.
@LearnAspNet. . . In your query with case expression, it will return 3 rows only when @schoolId is null. because null = null will evaluate as false.
1

Simply use or:

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

You have two separate conditions and this checks both of them.

3 Comments

This won't work because it won't return the 3rd row if SchoolId is not provided
@LearnAspNet . . . This does exactly what you are asking for. Why would you say the 3rd row would not be returned? This returns ALL rows when @schoolid is null.
Sorry, my bad. if you edit your answer in any way. I can upvote you. It does not let me change the vote
0

Check this out:

declare @schoolId int

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.