Michael Kingsmill
Michael Kingsmill

Reputation: 1863

Using correlated subquery value in main query

I am trying to use the query below (which works perfectly), as a subquery to an UPDATE statement, and need to reference the value CORRECT_DATE in that UPDATE statement. If I could successfully SELECT that value in this query, passing it up to the UPDATE would be easy, but I can't seem to select the correlated subquery value below AND use it in the inequality.

SELECT A.NAME, MAX(A.[START])
FROM dbo.TANK A
WHERE A.[CURRENT] = 0 AND A.[END] < (SELECT B.[START] AS CORRECT_DATE
                                          FROM dbo.TANK B
                         WHERE B.[CURRENT] = 1
                         AND A.NAME = B.NAME
                         AND A.TYPE = B.TYPE
                              AND A.COVER = B.COVER)

I have tried the following, but it doesnt recognize the alias in the WHERE clause:

SELECT A.NAME, MAX(A.[START]), (SELECT B.[START] AS CORRECT_DATE
                                          FROM dbo.TANK B
                         WHERE B.[CURRENT] = 1
                         AND A.NAME = B.NAME
                         AND A.TYPE = B.TYPE
                              AND A.COVER = B.COVER) as subvalue
FROM dbo.TANK A
WHERE A.[CURRENT] = 0 AND A.[END] < subvalue

Upvotes: 0

Views: 812

Answers (1)

HLGEM
HLGEM

Reputation: 96650

Why wouldn't you use a join? Correlated subqueries are performance killers that should be avoided where possible.

SELECT A.NAME
    , MAX(A.[START])
    , B.[START]                                           
FROM dbo.TANK A 
JOIN dbo.TANK B
    ON A.NAME = B.NAME 
    AND A.TYPE = B.TYPE
    AND A.COVER = B.COVER AND B.[CURRENT] = 1 
WHERE A.[CURRENT] = 0 AND A.[END] < B.[START]
     GROUP BY A.NAME, B.[START];

Upvotes: 2

Related Questions