数据库A表是一个树形结构的表,我要根据parentid返回每条数据处于第几层。顶层是parentid=0

解决方案 »

  1.   

    第二个表示数据表,第一个是想要的查询结果,就是生成一个flag字段用于记录是第几层
      

  2.   

    with a1
    as
    (
    select * from Tim_LinqTable
    ),
     a2 as
    (
     select * from a1  where a1.id=5
     union all
     select a1.* from a1  ,a2 where  a2.id=a1.Parent
    )
    仅供参考,递归的写法。。
      

  3.   

    我真是个天才,瞎弄还真整出来了!谢谢你的提示。我把代码贴出来WITH a1
    WITH test
    AS
    (

            SELECT ID,Name,ParentID,0 as flag FROM Table_tree where ParentID=0
            UNION ALL
            SELECT a.ID,a.Name,a.ParentID,B.flag+1 as flag FROM Table_tree A 
            INNER JOIN test B ON A.ParentID = B.ID
    )
    SELECT * FROM test