Wednesday, June 5, 2019

Add or ignore where conditions in SQL Server query based on a flag

Assume you want to select data from SQL Server based on a condition. But the condition should be considered only if another condition satisfies else it should return all data. How would you do that. Here is a sample program to achieve the solution.

declare @flagAll = 1;

Select *
from Students S
where @flagAll = 1
or S.Department = 'CSE'
In this example if the @flagAll is set to 1, then the first condition will be satisfied so the second condition will not be executed as it is OR condition, so all data will be returned. Else if @flagAll = 0 then the first condition will be failed, as it is OR condition the second condition S.Department = 'CSE' will be considered and all CSE department Student data will be returned.

If you have alternate solution, Kindly post as comment.

No comments:

Post a Comment