I have a question about sub-queries and case statements
I have two case statements in the same query:
- One has a sub-query that is used to determine if a column has a match.
- I’d like the other to check if theres a match [among other checks], then tag a value.
- However, t-SQL will not let me reference my first field (generated from the case statement) within my second case statement.
- This forces me to add the subquery into my second case statement and do away with the first case statement
- When I do this, my query goes from 13 seconds to 2.5 minutes
- When I remove the subquery altogether from my query, it takes 8 seconds to run
Question 1: Can case-statement-generated fields be referenced in subsequent case statements in the same query?
Question 2: Why does my query take only 5 seconds longer when I have the subquery in an isolated case statement but 2 minutes longer when that subquery is in a case statement that has 4-5 other checks?
1st Case Statement
CASE WHEN (SELECT xxx.xxx from xxx) THEN 'Y'
END AS "Match_Ind",
Second Case Statement
CASE WHEN condition 1 = true THEN 'cond1'
WHEN condition 2 = true THEN 'cond2'
WHEN Match_Ind = 'Y' THEN 'matched'
END AS "Match Detail"
You should consider posting your full query but if you want to reference the result of the first
CASEinside of anotherCASEstatement, then you can wrap it in aSELECTsimilar to this: