Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Conditional COLUMN in WHERE clause?

Author  Topic 

TheKai
Starting Member

16 Posts

Posted - 2013-06-08 : 18:43:20
I'm trying to determine which of two columns to query depending on the value of those columns. Normally, in standard programming, I would use an IF or CASE statement to transfer control... as I gather, CASE statements aren't control statements in TSQL, but rather return a value.

Here is what I'm trying to say: " I want results where either COL1 or COL2 are NULL and whichever column isn't null has a value greater than 5".

Something along the lines of...

SELECT COL1, COL2 FROM TABLE
WHERE
(COL1 IS NULL OR COL2 IS NULL) AND

IF COL1 IS NULL
COL2 > 5
ELSE IF COL2 IS NULL
COL1 > 5

Can this be done in TSQL?

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-06-08 : 19:04:34
What do you want to do when both col1 and col2 are not null, or when both are less than 5, and other combinations Some sample data would help. Perhaps this?
select
case
when col1 is null and col2 > 5 then col2
when col2 is null and col1 > 5 then col1
else null
end as Col1OrCol2
from
YourTable
Go to Top of Page

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2013-06-10 : 01:46:16
-- May be this?
SELECT COL1, COL2 FROM TABLE
WHERE ((COL1 IS NULL AND COL2 > 5) OR (COL2 IS NULL AND COL1 > 5))

--
Chandu
Go to Top of Page
   

- Advertisement -