• Allow me to make amends for my prior transgression with my take on the Dynamic SQL version:

    WITH UnravelHiearchy AS

    (

    SELECT Level=0, Car, Child, Parent, Category_Name

    FROM #TestEnvironment

    WHERE Car IS NOT NULL

    UNION ALL

    SELECT Level+1, a.Car, b.Child, b.Parent, b.Category_Name

    FROM UnravelHiearchy a

    JOIN #TestEnvironment b ON a.Parent = b.Child

    )

    SELECT Level, Car, Child, Parent, Category_Name

    INTO #Temp

    FROM UnravelHiearchy;

    DECLARE @SQL NVARCHAR(MAX);

    SELECT @SQL = '

    SELECT Car' +

    (

    SELECT ' ,Level' + CAST(n AS VARCHAR) + '=MAX(CASE WHEN Level = ' +

    CAST(n AS VARCHAR) + ' THEN Category_name END)'

    FROM

    (

    SELECT TOP

    (

    (SELECT TOP 1 COUNT(*) FROM #Temp GROUP BY Car ORDER BY 1 DESC) - 1

    ) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM sys.all_columns

    ) a(n)

    ORDER BY n

    FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'

    )

    + ' FROM #Temp

    GROUP BY Car

    ORDER BY Car;'

    --PRINT @SQL;

    EXEC (@SQL);

    GO

    DROP TABLE #Temp;


    My mantra: No loops! No CURSORs! No RBAR! Hoo-uh![/I]

    My thought question: Have you ever been told that your query runs too fast?

    My advice:
    INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?
    The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.

    Need to UNPIVOT? Why not CROSS APPLY VALUES instead?[/url]
    Since random numbers are too important to be left to chance, let's generate some![/url]
    Learn to understand recursive CTEs by example.[/url]
    [url url=http://www.sqlservercentral.com/articles/St