October 21, 2010 at 9:12 am
Dear All,
I have one sql table in the following structure (parent child up to n level)
Id ParentID Caption
--------------------------
1 0 Caption1
2 1 Caption2
3 2 Caption3
i want the output in the following format
Id ParentID Caption FullCaption
---------------------------------------------------
1 0 Caption1 Caption1
2 1 Caption2 Caption1\Caption2
3 2 Caption3 Caption1\Caption2\Caption3
Hope someone can provide the query.
Thanks in advance
Denny
October 21, 2010 at 9:57 am
DECLARE @t TABLE(Id INT, ParentID INT, Caption VARCHAR(10))
INSERT INTO @t(Id, ParentID, Caption)
SELECT 1, 0, 'Caption1' UNION ALL
SELECT 2, 1, 'Caption2' UNION ALL
SELECT 3, 2, 'Caption3';
WITH CTE AS (
SELECT Id, ParentID, Caption, CAST(Caption AS VARCHAR(MAX)) AS FullCaption
FROM @t
WHERE ParentID=0
UNION ALL
SELECT a.Id, a.ParentID, a.Caption, c.FullCaption + '\' + a.Caption
FROM @t a
INNER JOIN CTE c ON c.Id = a.ParentID)
SELECT Id, ParentID, Caption, FullCaption
FROM CTE;
____________________________________________________
Deja View - The strange feeling that somewhere, sometime you've optimised this query before
How to get the best help on a forum
http://www.sqlservercentral.com/articles/Best+Practices/61537October 21, 2010 at 10:53 pm
Thanks Mark..
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply