sqlServer 2005 sql 2005 sql 트 리, 하위 노드 찾기 최상 위, 최상 위 노드, 중간 노드 무시

2049 단어 sql
create table tb(id varchar(3) , pid varchar(3) , name varchar(10))
insert into tb values('001' , null  , '   ')
insert into tb values('002' , '001' , '   ')
insert into tb values('003' , '001' , '   ')
insert into tb values('004' , '002' , '   ')
insert into tb values('005' , '003' , '   ')
insert into tb values('006' , '003' , '   ')
insert into tb values('007' , '003' , '   ')
insert into tb values('008' , '007' , '   ')
insert into tb values('009' , '007' , '   ')
insert into tb values('010' , '007' , '   ')
go

--               
create function f_pid(@id varchar(3)) returns @t_level table(id varchar(3))
as
begin
  insert into @t_level select @id
  select @id = pid from tb where id = @id and pid is not null
  while @@ROWCOUNT > 0
  begin
    delete from @t_level
    insert into @t_level select @id select @id = pid from tb where id = @id and pid is not null
  end
  return
end
go

--      005(   )       
select a.* from tb a , f_pid('005') b where a.id = b.id 
/*
id   pid  name       
---- ---- ---------- 
001  NULL    

(        1  )
*/

--      002(   )       
select a.* from tb a , f_pid('002') b where a.id = b.id 
/*
id   pid  name       
---- ---- ---------- 
001  NULL    

(        1  )
*/

--      001(   )       
select a.* from tb a , f_pid('001') b where a.id = b.id 
/*
id   pid  name       
---- ---- ---------- 
001  NULL    

(        1  )


drop table tb
drop function f_pid
*/

검 은 머리:http://heisetoufa.iteye.com/

좋은 웹페이지 즐겨찾기