0

The select * from MyTable gives the following result, enter image description here

Now I would like to get ids of all childs if I pass the id of 'Chest'.

For example, if I pass id of 'ChestOne', I would like to get the following table

enter image description here

I tried the following, but could not get the result

;WITH Temp_CTE AS
(
SELECT 
     id
    ,name
    ,parent_id
FROM dbo.MyTable
WHERE id = '12D390AE-FF28-4D50-B3A2-A6CC4E6E02A9'
UNION ALL 
SELECT 
     CS.id
    ,CS.name
    ,CS.parent_id
FROM dbo.MyTable CS
INNER JOIN Temp_CTE ON CS.id =  Temp_CTE.parent_id

)
SELECT * FROM Temp_CTE

How can I do it in SQL Server 2008 ?

1
  • 2
    Try to change your join around. INNER JOIN Temp_CTE ON CS.parent_id = Temp_CTE.id Mar 2, 2012 at 7:34

2 Answers 2

2
declare @MyTable table 
(
  id char(2),
  name varchar(10),
  parent_id char(2)
)  

insert into @MyTable values
('54', 'Chest Two', '12'),
('CD', 'InCOne', '6D'),
('6D', 'ChestOne', '12'),
('12', 'Chest', '00')

;WITH Temp_CTE AS
(
SELECT 
     id
    ,name
    ,parent_id
FROM @MyTable
WHERE id = '6D'
UNION ALL 
SELECT 
     CS.id
    ,CS.name
    ,CS.parent_id
FROM @MyTable CS
INNER JOIN Temp_CTE ON CS.parent_id =  Temp_CTE.id

)
SELECT * FROM Temp_CTE

Result:

id   name       parent_id
---- ---------- ---------
6D   ChestOne   12
CD   InCOne     6D
2

I think it should be:

;WITH Temp_CTE AS
(
SELECT 
     id
    ,name
    ,parent_id
FROM dbo.MyTable
WHERE id = '12D390AE-FF28-4D50-B3A2-A6CC4E6E02A9'
UNION ALL 
SELECT 
     CS.id
    ,CS.name
    ,CS.parent_id
FROM dbo.MyTable CS
INNER JOIN Temp_CTE ON CS.parent_id =  Temp_CTE.id

)
SELECT * FROM Temp_CTE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.