SQL 父子表,显示表中每条记录所在层级

1.sqlserer 中有一张父子关系表,表结构如下:

CREATE TABLE [dbo].[testparent](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](50) NULL,
    [parentID] [int] NULL,
 CONSTRAINT [PK_testparent] PRIMARY KEY CLUSTERED 

2.其中的数据类似:

3.用 CET 递归的方式返回每条记录的层级,其中 lev 为层级, where 后面的条件需要注意

复制代码
with tree as(
    select id,
    name,
    parentID,
    lev=1
    from testparent
    where name='江苏省'
    UNION ALL
        select 
        b.ID,
        b.name,
        b.parentID,
        lev = tree.lev+1
        from tree
        inner join testparent b on tree.ID=b.parentID    #注意此处的 tree.ID与b.parentID
)
select * from tree
复制代码

4.结果为:

 

posted @ 2020-04-13 10:51  我是真的大米  阅读(598)  评论(0编辑  收藏  举报