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
Why wouldn’t you use a join? Correlated subqueries are performance killers that should be avoided where possible.