Jeff Moden (6/30/2014)
tafinami (6/30/2014)
DECLARE c CURSOR READ_ONLY FAST_FORWARD FORSELECT 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
In this case, a cursor isn't the worst thing in the world. However, take a look at the following articles...
Or this one, if Jeff's wonderful solutions on steroids overwhelm you:
The Performance of Traversing a SQL Hierarchy [/url]
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