OverflowUser OverflowUser - 7 months ago 8
SQL Question

Get row from table based on parameter

I want to get row from based on parameter value. Either it could be value 'ABC' or NULL. Below is the source table and expected result, which I'm trying to achieve.

SourceTable

column1 column2
--------------------------
value1 NULL
value2 ABC


Tried with query, but it is getting two rows which are with value1 and value2.

Declare @Param1 varchar(20) = 'ABC'

Select *
from SourceTable
where column2 = @Param1 Or column2 is NULL


If value is 'ABC' then Result -

column1 column2
--------------------------
value2 ABC


If value is NULL then Result -

column1 column2
--------------------------
value1 NULL

Answer

Perhaps this would work for you?

select * 
from SourceTable 
where column2 = @Param1 or (@Param1 is null and column2 is null)