Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

t-sql recursive query

Based on an existing table I used CTE recursive query to come up with following data. But failing to apply it a level further.

Data is as below

id    name     parentid
--------------------------
1     project   0
2     structure 1
3     path_1    2
4     path_2    2
5     path_3    2
6     path_4    3
7     path_5    4
8     path_6    5

I want to recursively form full paths from the above data. Means the recursion will give the following output.

FullPaths
-------------
Project
Project\Structure
Project\Structure\Path_1
Project\Structure\Path_2
Project\Structure\Path_3
Project\Structure\Path_1\path_4
Project\Structure\Path_2\path_5
Project\Structure\Path_3\path_6

Thanks

like image 777
stackoverflowuser Avatar asked Apr 29 '10 18:04

stackoverflowuser


People also ask

Can we write recursive query in SQL?

Recursion is achieved by WITH statement, in SQL jargon called Common Table Expression (CTE). It allows to name the result and reference it within other queries sometime later. Naming the result and referencing it within other queries.

How recursive query works in SQL?

A recursive query is one that is defined by a Union All with an initialization fullselect that seeds the recursion. The iterative fullselect contains a direct reference to itself in the FROM clause. There are additional restrictions as to what can be specified in the definition of a recursive query.

How do you achieve recursive queries in SQL Server?

First, execute the anchor member to form the base result set (R0), use this result for the next iteration. Second, execute the recursive member with the input result set from the previous iteration (Ri-1) and return a sub-result set (Ri) until the termination condition is met. Third, combine all result sets R0, R1, …

What is the difference between CTE and recursive CTE?

A CTE can be recursive or non-recursive. A recursive CTE is a CTE that references itself. A recursive CTE can join a table to itself as many times as necessary to process hierarchical data in the table. CTEs increase modularity and simplify maintenance.


1 Answers

Here's an example CTE to do that:

declare @t table (id int, name varchar(max), parentid int)

insert into @t select 1,     'project'  , 0
union all select 2,     'structure' , 1
union all select 3,     'path_1'    , 2
union all select 4,     'path_2'    , 2
union all select 5,     'path_3'    , 2
union all select 6,     'path_4'    , 3
union all select 7,     'path_5'    , 4
union all select 8,     'path_6'    , 5

; with CteAlias as (
    select id, name, parentid
    from @t t
    where t.parentid = 0
    union all
    select t.id, parent.name + '\' + t.name, t.parentid
    from @t t
    inner join CteAlias parent on t.parentid = parent.id
)
select * 
from CteAlias
like image 198
Andomar Avatar answered Nov 02 '22 03:11

Andomar