日期:2014-05-16 浏览次数:20807 次
;with t(XuHao, ManName, ManPrior)
as
(
select 1,'马雷',null
union all select 2,'刘三','胡涛'
union all select 3,'郑平','马雷'
union all select 4,'胡涛','郑平'
union all select 5,'陈雨','刘三'
),
tt
as
(
select manname,manprior,1 as level from t
where manprior is null
union all
select t.ManName,t.ManPrior,level + 1
from tt
inner join t
on tt.ManName = t.ManPrior
)
select manname
from tt
/*
manname
马雷
郑平
胡涛
刘三
陈雨
*/
if object_id('Tempdb..#t') is not null drop table #t
create table #t(
xuhao int identity(1,1) not null,
ManName nvarchar(10) null,
ManPrior nvarchar(10) null
)
Insert Into #t
select '马雷',null union all
select '刘三','胡涛' union all
select '郑平','马雷' union all
select '胡涛','郑平' union all
select '陈雨','刘三'
;with cte as(
select a.*,isnull(b.xuhao,0) as pid from #t a left join #t b on a.ManPrior=b.ManName
)
select xuhao,ManName,ManPrior from cte order by pid
--------------
xuhao ManName ManPrior
----------- ---------- ----------
1 马雷 NULL
3 郑平 马雷
5 陈雨 刘三
4 胡涛 郑平
2 刘三 胡涛
(5 行受影响)
--drop table tb
create table tb(XuHao int, ManName nvarchar(20), ManPrior nvarchar(20))
insert into tb
select 1,'马雷',null
union all select 2,'刘三','胡涛'
union all select 3,'郑平','马雷'
union all select 4,'胡涛','郑平'
union all select 5,