• tafinami (6/30/2014)


    DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR

    SELECT Id FROM Tree_Table WHERE Id NOT IN (SELECT DISTINCT ParentId FROM Tree_Table WHERE ParentId IS NOT NULL)

    DECLARE @IdPk INT

    OPEN c

    FETCH NEXT FROM c INTO @IdPk

    WHILE (@@FETCH_STATUS = 0)

    BEGIN

    DECLARE @NodeValue VARCHAR(MAX)

    SET @NodeValue = ''

    WHILE(EXISTS(SELECT * FROM Tree_Table WHERE Id=@IdPk))

    BEGIN

    SELECT @NodeValue=Name+'/'+@NodeValue,

    @IdPk=ParentId

    FROM Tree_Table

    WHERE id=@IdPk

    END

    PRINT 'Parent to Leaf: ' + LEFT(@NodeValue,LEN(@NodeValue)-1)

    FETCH NEXT FROM c INTO @IdPk

    END

    CLOSE c

    DEALLOCATE c

    To get hierarchy and tree view data

    In this case, a cursor isn't the worst thing in the world. However, take a look at the following articles...

    http://www.sqlservercentral.com/articles/Hierarchy/94040/

    http://www.sqlservercentral.com/articles/T-SQL/94570/

    --Jeff Moden


    RBAR is pronounced "ree-bar" and is a "Modenism" for Row-By-Agonizing-Row.
    First step towards the paradigm shift of writing Set Based code:
    ________Stop thinking about what you want to do to a ROW... think, instead, of what you want to do to a COLUMN.

    Change is inevitable... Change for the better is not.


    Helpful Links:
    How to post code problems
    How to Post Performance Problems
    Create a Tally Function (fnTally)