if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[Name] varchar(10),[ParentID] int)
insert [tb]
select 382,'调度员岗位',-1 union all
select 383,'基础知识',382 union all
select 390,'电工基础',383 union all
select 1995,'test知识点',390
go
--select * from [tb]
declare @id int
set @id=1995
--set @id=390
select ID,Name,ParentID into # from tb where id=@id
while @@rowcount>0
insert #
select a.ID,a.Name,a.ParentID
from tb a join # b
on a.ID=b.ParentID and a.ID not in(select ID from #)
select * from #
--@id=1995
/*
ID Name ParentID
----------- ---------- -----------
390 电工基础 383
383 基础知识 382
382 调度员岗位 -1
1995 test知识点 390
(4 行受影响)
*/
--@id=390
/*
ID Name ParentID
----------- ---------- -----------
383 基础知识 382
382 调度员岗位 -1
390 电工基础 383
(3 行受影响)
*/
drop table #
http://topic.youkuaiyun.com/u/20090427/12/3933fd09-c153-46c0-b584-3a4a40208945.html