I want to select all column values irrespective of NULL as column value.
My problem is when I try to select values using IS NULL I'm getting such records also these having NULL as a value.
declare @status varchar(50)=NULL
declare @path varchar(50)= 'India'
select
*
from [vwMYDATA]
where
Path like '%' + @path + '%' and
(Status = @status or @status IS NULL)
vwMYDATA
path status
INDIA1 NULL
INDIA2 close
INDIA3 open
If I execute above query I'm getting all records whose status column has NULL value. Expected is if no status value specified show all status records:
path status
INDIA1 NULL
INDIA2 close
INDIA3 open
It is showing:
path status
INDIA1 NULL
I'm passing these 2 parameters to stored procedure which is having this select statement.
How can I filter out and show all the records if status is not given as input?
6条答案
按热度按时间fiei3ece1#
3okqufwl2#
You need to change the WHERE clause to a Case statement if you want different actions based on whether the @status varchar is NULL.
This might be inefficient and nonperformant. For performance, it would be better to have a completely different query that matches based on NULL or not, so that proper indexing can be applied.
fcipmucu3#
If you're happy to always filter out records with a null status (which it seems you are) then this should work:
agxfikkp4#
Just try remove
or @status IS NULL
condition2ekbmq325#
You need to change your condition like below:
you just need to change the place of condition because the conditions check from first, so now if the @status will be null, query don't check next condition.
0s0u357o6#
Get NUll Value Records on Status select * from vwMYDATA where status is null
Get Not NUll Value Records on Status select * from vwMYDATA where status is not null