Domanda

I have this table in sql:

TopicID      Code       Name       ParentID
-------      ----       ----       --------
1            001        Parent1       0
2            001        Childp1       1
3            002        Parent2       0
4            001        Childp2       3
5            001        Childp21      4
.
.
etc

Now I want to 1.get sql select which retrives me the last node? (which I did by following line)

select * from accounting.topics where topicid not in(select parentid from accounting.topics)

and the result is:

TopicID      Code       Name       ParentID  |    newcolumn
-------      ----       ----       --------  |   ---------
2            001        Childp1       1      |    001001
5            001        Childp21      4      |    002001001

2.Important one is to show the concat of code from first to last node of each row in above result,like newcolumn in above,Actually I can't produce the newcolumn ? *notice that the nodes level are unlimited.

È stato utile?

Soluzione

This could be done relatively easy with recursive common table expressions:

with cte as (
    select
        T1.TopicID, T1.Code, T1.Name, T1.ParentID,
        T1.ParentID as NewParentID,
        cast(T1.Code as nvarchar(max)) as NewColumn
    from Table1 as T1
    where not exists (select * from Table1 as T2 where T2.ParentID = T1.TopicID)
    union all
    select
        c.TopicID, c.Code, c.Name, c.ParentID,
        T1.ParentID as NewParentID,
        c.NewColumn + cast(T1.Code as nvarchar(max)) as NewColumn
    from cte as c
        inner join Table1 as T1 on T1.TopicID = c.NewParentID
)
select
    c.TopicID, c.Code, c.Name, c.ParentID, c.NewColumn
from cte as c
where c.NewParentID = 0

sql fiddle demo

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top