sql2005--建立测试环境
declare @t table (id varchar(10),name varchar(10),parentId varchar(10))
--插入数据
insert into @t
select '1','root','-1' union
select '2','牛','1' union
select '3','猪','1' union
select '4','水牛','2' union
select '5','小牛','4' union
select '6','大牛','4' union
select '7','红牛','6' union
select '8','小猪','3' union
select '9','大猪','3'--测试语句
;with t (id, name, parentId, rootName)
as(
    select a.id, a.name, a.parentId, a.name  
    from @t as a
    where parentId =1 
  union all     
    select a.id, a.name, a.parentId, rootName
    from @t a
    join   t as b  
      on a.parentId = b.id
)
select * from t /*
2 牛 1 牛
3 猪 1 猪
8 小猪 3 猪
9 大猪 3 猪
4 水牛 2 牛
5 小牛 4 牛
6 大牛 4 牛
7 红牛 6 牛
*/