user1723982
user1723982

Reputation: 69

TSQL where case

I need the correct tsql syntax for this problem :

Select * from table where var_A='10'
select * from table where var_B='10'

When to use var_A or var_B depends on the value of var_C

So when var_c='something' use var_A='10' else var_B='10'

Upvotes: 4

Views: 10055

Answers (3)

Vishwanath Dalvi
Vishwanath Dalvi

Reputation: 36671

This how you use case statement within where clause.

select * from table
where ( case when var_c = 'something' 
        then var_a
        else 
            var_b
        end
      )

Upvotes: 0

BreakingBrad
BreakingBrad

Reputation: 256

Ian probably has the best answer available but I thought I would supply another answer for a different (although less flexible) method in case it helps:

IF var_c = 'something' BEGIN
    SELECT * FROM [table] WHERE var_a = '10'
END
ELSE BEGIN
    SELECT * FROM [table] WHERE var_b = '10'
END

Upvotes: 2

Ian Preston
Ian Preston

Reputation: 39586

select *
from [table]
where case when var_c = 'something' then var_a else var_b end = '10'

SQL Fiddle with demo.

Upvotes: 5

Related Questions