Click here to Skip to main content
15,891,907 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to compare a variable in where condition to second column if first column is null ?

my sql query is like below


SQL
select * from table where column1 = @variable

now i want is if the value of column1 is null then it should check with column two. if the value of column1 is not null it should compare with that column only.


SQL
select * from table where column2 = @variable
Posted

SQL
select * from table where column1 = @variable OR (column1 IS NULL AND column2 = @variable)
 
Share this answer
 
v3
SQL
select * from table
where
 @variable = IsNull([Column1], [Column2])
 
Share this answer
 
Try like this :

SQL
select * from table 
where 
Case WHEN column1 is not null 
THEN
column1 
 ELSE
 column2 END = @variable
 
Share this answer
 
select * from table where column1 = @variable
CASE WHEN IsNull(column1)=1 THEN column1==@variable ELSE column2==@variable END
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900