Home Change column being used in WHERE condition based on IF condition
Reply: 2

Change column being used in WHERE condition based on IF condition

Nugs
1#
Nugs Published in 2018-01-11 19:22:19Z

I apologize for the title - i was struggling coming up with something better.

Been doing some research on this and did find some close examples, however this is not quite what i need.

Basically i have a table with two columns that i want to evaluate under certain conditions. Column 1 is a identifier that can also be null. Column 2 is a SessionId that can change also.

Primarily i key off of column1, but when column1 is null i would like to key off of column2 instead. The example i linked above doesn't change the column being evaluated in the WHERE clause, only the value being used to evaluate the clause.

Here is some pseudo code to illustrate what i am trying to do:

SELECT * FROM MyTable
WHERE
IF Column1 NOT NULL
   Column1 = @myvariable1
ELSE
   Column2 LIKE '%' + @myvariable2 + '%'

Is something like this even possible? Can i switch the column to be evaluated in the WHERE clause based on the value of one of the columns?

I hope all that makes sense.

TIA

lad2025
2#
lad2025 Reply to 2018-01-11 19:25:02Z

You could use CASE:

SELECT * 
FROM MyTable
WHERE (CASE WHEN Column1 IS NOT NULL AND Column1 = @myvariable1 THEN 1
            WHEN Column2 LIKE '%' + @myvariable2 + '%' THEN 1
            ELSE 0
      END) = 1;
Paparazzi
3#
Paparazzi Reply to 2018-01-11 20:42:04Z
WHERE  Column1 = @myvariable1
OR   ( Column1 IS NULL AND Column2 LIKE '%' + @myvariable2 + '%' )
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.328246 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO