table 1
---------
id parentId name
1 00000 a
2 1 a.a
3 2 a.a.a
.
.
.
通过任意的一个子级ID 获取最顶级的sql (不确定有多少级)
------解决方案--------------------
- SQL code
while(parentId <>00000)begin declare @ID int select id from tableName where id= (select parentId from tableName where [email protected])end
------解决方案--------------------
看楼主例子,作为顶级ID,parentId的值为‘00000’。
- SQL code
create table t1( id int, pid varchar(5), name varchar(10))insert into t1select 1, '00000', 'a' union allselect 2, '1', 'a.a' union allselect 3, '2', 'a.a.a' union allselect 4, '00000', 'b' union allselect 5, '4', 'b.b' union allselect 6, '5', 'b.b.b'select * from t1;with aaa as(select * from t1 where id=3union allselect t1.* from t1 inner join aaa on t1.id=aaa.pid)select * from aaa where pid='00000'--------------------id pid name1 00000 a