zoukankan      html  css  js  c++  java
  • 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.结果为:

  • 相关阅读:
    js中级-函数封装
    js中级-11.7
    js中级-11.5
    js中级-11.2
    js中级-this
    js中级-作用域链
    10.23
    10.22
    10.19js
    10.18
  • 原文地址:https://www.cnblogs.com/chenqingbin/p/12689933.html
Copyright © 2011-2022 走看看