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
)
select * from tree

4.结果为:

猜你喜欢

转载自www.cnblogs.com/allen-zqw/p/10890446.html