Question : Correlated subquery in THEN clause of CASE statement

Is it possible to use a correlated subquery in the THEN clause of a CASE/WHEN/THEN statement in Transact SQL?  

Here's what I have so far...below, TABLE_X is an alias to a table used in the main SELECT statement:

SELECT  
    FieldA,
    FieldB,

    FieldC =
        CASE
            WHEN TABLE_X.ECL_DATE IS NULL THEN (SELECT RECL_DATE FROM TABLE_Y WHERE ID = TABLE_X.ID)
            ELSE TABLE_X.ECL_DATE
        END,

    FieldD,
    FieldE,
    etc.

Basically what I need to do is evaluate if the ECL_DATE from TABLE_X is null.  If it is, then do a subquery to return in its place a completely different value from a different table (but still correlated to the base SELECT via TABLE_X.ID).

Is this doable?

Answer : Correlated subquery in THEN clause of CASE statement

This is doable

You basically have the syntax right - but you do not want an = sign

SELECT  
    FieldA,
    FieldB,
        CASE
            WHEN TABLE_X.ECL_DATE IS NULL THEN (SELECT RECL_DATE FROM TABLE_Y WHERE ID = TABLE_X.ID)
            ELSE TABLE_X.ECL_DATE
        END As FieldC,
    FieldD,
    FieldE,
    .......

Also make sure that (SELECT RECL_DATE FROM TABLE_Y WHERE ID = TABLE_X.ID) returns only one row
Random Solutions  
 
programming4us programming4us