首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

通过子级取最顶级的sql 如何写!

2012-03-31 
通过子级取最顶级的sql 怎么写!!!!table 1---------idparentIdname100000a21a.a32a.a.a...通过任意的一个

通过子级取最顶级的sql 怎么写!!!!
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 id=@ID)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 

热点排行