0

What is the best solution : I have a table in sqlserver with these contents .

PARENT CHILD  Level 
A        B      0
B        C      1
C        D      2
D        E      3

I need a query to create this result : A/B/C/D/E

4
  • i am not sure about your result..would you please explain ? Commented Nov 23, 2014 at 11:02
  • I think there is no GROUP_CONCAT function in MSSQL. Commented Nov 23, 2014 at 11:04
  • I want to have a parent child relation in a row that sorted base on relation . Commented Nov 23, 2014 at 11:06
  • plz check this link,i think this is useful for you link Commented Nov 23, 2014 at 11:12

2 Answers 2

1

You can use a recursive CTE for this:

with cte as (
       select t.parent as p, t.parent as c, 0 as lev
       from table t
       where not exists (select 1 from t t2 where t2.child = t.parent)
       union all
       select cte.p, t.child, lev + 1
       from cte join
            table t
            on cte.c = t.parent
     )
select stuff((select '/' + cte2.c
              from cte cte2
              where cte2.p = cte.p
              order by cte2.lev
              for xml path ('')
             ), 1, 1, '') as path
from cte
group by cte.p;

Here is a SQL Fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

Use Coalesce to combine rows into single column separated by '/' delimiter

DECLARE @path VARCHAR(8000) = (SELECT parent FROM test WHERE LEVEL = 0)

SELECT @path = COALESCE(rtrim(@path) + '/', '') + child FROM test

SELECT @path 

1 Comment

thnks @Konstantin for your suggestion, i had answered this as per original request which later on got changed.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.