View level number in SQL recursive table

I have the following table:

--------------------------------------------
ID      ParentID     Item  
--------------------------------------------
1                    root
2       1            AA
3       1            BB
4       1            CC
5       1            DD
6       2            A1
7       6            A11
ff.

I want to get the following result:

ID      ParentID     Item         Level
---------------------------------------------
1                    root         0
2       1            AA           1
3       1            BB           1
4       1            CC           1
5       1            DD           1
6       2            A1           2
7       6            A11          3
ff.
  • What is the idea of ​​creating a new column level? Creates a new column and adds a formula or something like a calculated or perhaps function?
  • How can I achieve this on t-sql?

Thank.

+4
source share
2 answers

You would use a recursive CTE:

with cte as (
      select t.id, t.parentid, t.item, 0 as lvl
      from t
      where parentid is null
      union all
      select t.id, t.parentid, t.item, cte.lvl + 1 as lvl
      from t join
           cte
           on t.parentid = cte.id
     )
select *
from cte;

Saving this data in a table. Is cumbersome because you need to update it. You can simply compute it on the fly when you need it.

+6
source

Just using DENSE_RANK:

DECLARE @YourTable TABLE(ID INT,ParentID VARCHAR(10),Item VARCHAR(10))
INSERT into @YourTable VALUES(1,' ','root')
INSERT into @YourTable VALUES(2,'1','AA')
INSERT into @YourTable VALUES(3,'1','BB')
INSERT into @YourTable VALUES(4,'1','CC')
INSERT into @YourTable VALUES(5,'1','DD')
INSERT into @YourTable VALUES(6,'2','A1')
INSERT into @YourTable VALUES(7,'6','A11')


SELECT ID,ParentID,Item
    ,(DENSE_RANK() OVER(ORDER BY ISNULL(NULLIF(ParentID,''),0)))-1 [Level]
FROM @YourTable

Conclusion:

ID  ParentID    Item    Level
1               root    0
2   1           AA      1
3   1           BB      1
4   1           CC      1
5   1           DD      1
6   2           A1      2
7   6           A11     3

Hope this helps you.

0
source

Source: https://habr.com/ru/post/1695450/


All Articles