Pillowsky
Pillowsky

Reputation: 9

How to apply 'case when' result to the where condition in SQL 2008 query

I'm working with the 'case when' statement in my query and doing some experiments. I tried to search for this problem but I am unable to put it in words.

my query problem example:

Select (a really long case when statement) as result from tablename where result=1 

is there any way to also put 'result' to the 'where' condition?

Upvotes: 0

Views: 68

Answers (1)

Charlieface
Charlieface

Reputation: 71628

Yes. The easiest way is to use CROSS APPLY (VALUES...

SELECT v.MyValue
FROM tablename
CROSS APPLY (VALUES (complex_expression_here) ) v(MyValue)
WHERE v.MyValue = 1

You could also place it in a derived table, but I find that more verbose

SELECT *
FROM (
    SELECT complex_expression_here AS MyValue
    FROM tablename
) t
WHERE v.MyValue = 1

Upvotes: 0

Related Questions