表结构:
id parent_id name数据:
0             A
1    0        a
2    0        b
3    1        aa
4    1        saqwqw
5    2        ewqe
6    2        w112。。
我想写个sql,根据已知id上溯得到这个id的第二级数据的name,而不是根A(也就是在我列出的数据中始终得到的是a或者b这两个name,而不是A.打个比方)

解决方案 »

  1.   

    declare @id int
    set @id=2
    ;with f as
    (
    select * from tb  where id=@id
    union all
    select a.* from tb a join f on a.parent_id =f.id
    )
    select name from f
      

  2.   

    create table tb(id int,parent_id int,name nvarchar(10))
    insert into tb select 0,null,'A'
    insert into tb select 1,0,'a'
    insert into tb select 2,0,'b'
    insert into tb select 3,1,'aa'
    insert into tb select 4,1,'saqwqw'
    insert into tb select 5,2,'ewqe'
    insert into tb select 6,2,'w112'
    go
    declare @id int
    set @id=5
    ;with cte as(
    select * from tb where id=@id
    union all
    select a.* from tb a inner join cte b on a.id=b.parent_id where a.id<>0
    )select * from cte a where not exists(select 1 from cte where id<a.id)
    go
    drop table tb
    /*
    id          parent_id   name
    ----------- ----------- ----------
    2           0           b(1 行受影响)*/
      

  3.   

    ;with cte as是什么意思?我是2000的库
      

  4.   

    create table tb(id int,parent_id int,name nvarchar(10))
    insert into tb select 0,null,'A'
    insert into tb select 1,0,'a'
    insert into tb select 2,0,'b'
    insert into tb select 3,1,'aa'
    insert into tb select 4,1,'saqwqw'
    insert into tb select 5,2,'ewqe'
    insert into tb select 6,2,'w112'
    go
    declare @id int
    set @id=5
    ;with cte as(
    select * from tb where id=@id
    union all
    select a.* from tb a inner join cte b on a.id=b.parent_id where a.id<>0
    )select * from cte a where not exists(select 1 from cte where id<a.id)
    go
    drop table tb
    /*
    id          parent_id   name
    ----------- ----------- ----------
    2           0           b(1 行受影响)*/
    这个应该可以,但我的执行提示:在关键字 'with' 附近有语法错误。