Thursday, August 11, 2011

Self-join with nested select query in T-SQL


Is it possible to join a nested select statement with itself (without writing it out twice and running it twice)
Something like this would be ideal
SELECT P.Child, P.Parent, Q.Parent AS GrandParentFROM (SELECT Child, Parent FROM something-complex) AS PLEFT JOIN P AS Q ON Q.Child = P.Parent


50% possible. You can use a CTE to avoid writing it twice but it will still execute twice.
;WITH p
     AS (SELECT child,
                parent
         FROM   something-complex)
SELECT p.child,
       p.parent,
       q.parent AS grandparentFROM   p
       LEFT JOIN p AS q
         ON q.child = p.parent  
If the query is expensive you would need to materialize it into a table variable or #temp table to avoid the self join causing two invocations of the underlying query