Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 Recursion in T-SQL

Author  Topic 

rockstar283
Yak Posting Veteran

96 Posts

Posted - 2011-07-22 : 17:54:44
I have a table XYZ with following data..

create table XYZ(parent_node_id int, child_id int)

insert into XYZ select 0000000000,0000000001
insert into XYZ select 0000000000,0000000124
insert into XYZ select 0000000000,0000007953
insert into XYZ select 0000007953,0000007954
insert into XYZ select 0000007954,0000007955
insert into XYZ select 0000007954,0000007956
insert into XYZ select 0000007957,0000007958
insert into XYZ select 0000007958,0000007959
insert into XYZ select 0000007958,0000007960
insert into XYZ select 0000007958,0000007961

The result should be

0000000000
------------0000000001
------------0000000124
------------0000007953
------------------------0000007954
------------------------------------0000007955
------------------------------------0000007956

0000007953
------------0000007954

0000007954
------------0000007955
------------0000007956

0000007957
------------0000007958
------------------------0000007959
------------------------0000007960
------------------------0000007961

0000007958
------------0000007959
------------0000007960
------------0000007961

I hope you are getting my question..
Its a recursive result where we first start with first parent_id..we select its child_id..then we make those child id as parent id and try to find their own child..
I think this can be done by recursive CTE..but I am not able to figure it out..can you guys please help me here..Thanks in advance


SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2011-07-22 : 18:13:42
Are you sure you have the correct output?
DECLARE	@Sample TABLE
(
ParentID CHAR(10) NOT NULL,
ChildID CHAR(10) NOT NULL
)

INSERT @Sample
VALUES ('0000000000', '0000000001'),
('0000000000', '0000000124'),
('0000000000', '0000007953'),
('0000007953', '0000007954'),
('0000007954', '0000007955'),
('0000007954', '0000007956'),
('0000007957', '0000007958'),
('0000007958', '0000007959'),
('0000007958', '0000007960'),
('0000007958', '0000007961')

;WITH cteSource(ParentID, ChildID, PathID, Iteration)
AS (
SELECT DISTINCT CAST(NULL AS CHAR(10)) AS ChildID,
ParentID,
CAST('/' + ChildID AS VARCHAR(MAX)) AS PathID,
CAST(0 AS INT) AS Iteration
FROM @Sample

UNION ALL

SELECT s.ParentID,
s.ChildID,
c.PathID + '/' + CAST(s.ChildID AS VARCHAR(MAX)) AS PathID,
c.Iteration + 1 AS Iteration
FROM cteSource AS c
INNER JOIN @Sample AS s ON s.ParentID = c.ChildID
)
SELECT REPLICATE('-', 10 * Iteration) + ChildID
FROM cteSource
GROUP BY REPLICATE('-', 10 * Iteration) + ChildID
ORDER BY MIN(PathID)



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page
   

- Advertisement -