SQL:树结构表选择

时间:2016-08-09 11:53:35

标签: sql

我有以下树形结构:

ROOT
  -Invoices
  -Documents
      -Word
      -Excel

存储在下表中:

LevelID; LevelParentID; LevelName
1001; -1; ROOT
1002; 1001;发票
1003; 1001;文件
1004; 1003;字
1005; 1003; Excel

'发票'和'文件'是ROOT(1001)级别的主要级别。和子级别' Word'和Excel' Excel'在文件(1003)级别下。

我想选择特定级别下的所有行。例如,如何:

  1. 选择整棵树?
  2. 选择'文件'下的所有级别水平?

1 个答案:

答案 0 :(得分:0)

Declare @Table table (LevelID int,LevelParentID int,LevelName varchar(50))
Insert into @Table values
(1001,-1,'ROOT'),
(1002,1001,'Invoices'),
(1003,1001,'Documents'),
(1004,1003,'Word'),
(1005,1003,'Excel')


Declare @Top  int = -1            -- 
Declare @Nest varchar(25) ='   '  -- Optional: Added for readability

;with cteHB (LevelID,LevelParentID,Lvl,LevelName) as (
     Select LevelID
           ,LevelParentID
           ,Lvl=1
           ,LevelName 
      From  @Table 
      Where @Top = case when @Top<0 then LevelParentID else LevelID end
     Union All
     Select cteCD.LevelID
           ,cteCD.LevelParentID,cteHB.Lvl+1
           ,cteCD.LevelName 
      From  @Table cteCD 
      Join cteHB on cteCD.LevelParentID = cteHB.LevelID)
Select LevelID
      ,LevelParentID
      ,Lvl
      ,LevelName = Replicate(@Nest,Lvl) + LevelName
 From cteHB

@ Top = -1

时返回
LevelID LevelParentID   Lvl    LevelName
1001    -1              1      ROOT
1002    1001            2         Invoices
1003    1001            2         Documents
1004    1003            3            Word
1005    1003            3            Excel

@ Top = 1003

时返回
LevelID LevelParentID   Lvl   LevelName
1003    1001            1      Documents
1004    1003            2         Word
1005    1003            2         Excel