--查詢ID = '009'的所有父節點 SET @ID = '009' ;WITH T AS ( SELECT ID , PID , NAME FROM TB WHERE ID = @ID UNION ALL SELECT A.ID , A.PID , A.NAME FROM TB AS A JOIN T AS B ON A.ID = B.PID ) SELECT * FROM T ORDER BY ID /* ID PID NAME ---- ---- ---------- 001 NULL 廣東省 003 001 深圳市 007 003 寶安區 009 007 龍華鎮
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_pid1(@id varchar(3)) returns varchar(100) as begin declare @re_str as varchar(100) set @re_str = '' select @re_str = name from tb where id = @id while exists (select 1 from tb where id = @id and pid is not null) begin select @id = b.id , @re_str = b.name + ',' + @re_str from tb a , tb b where a.id = @id and a.pid = b.id end return @re_str end go --查詢各節點的父路徑函數(從子到父) create function f_pid2(@id varchar(3)) returns varchar(100) as begin declare @re_str as varchar(100) set @re_str = '' select @re_str = name from tb where id = @id while exists (select 1 from tb where id = @id and pid is not null) begin select @id = b.id , @re_str = @re_str + ',' + b.name from tb a , tb b where a.id = @id and a.pid = b.id end return @re_str end go select * , dbo.f_pid1(id) [路徑(從父到子)] , dbo.f_pid2(id) [路徑(從子到父)] from tb order by id drop function f_pid1 , f_pid2 drop table tb /* id pid name 路徑(從父到子) 路徑(從子到父) ---- ---- ------ --------------------------- ---------------------------- 001 NULL 廣東省 廣東省 廣東省 002 001 廣州市 廣東省,廣州市 廣州市,廣東省 003 001 深圳市 廣東省,深圳市 深圳市,廣東省 004 002 天河區 廣東省,廣州市,天河區 天河區,廣州市,廣東省 005 003 羅湖區 廣東省,深圳市,羅湖區 羅湖區,深圳市,廣東省 006 003 福田區 廣東省,深圳市,福田區 福田區,深圳市,廣東省 007 003 寶安區 廣東省,深圳市,寶安區 寶安區,深圳市,廣東省 008 007 西鄉鎮 廣東省,深圳市,寶安區,西鄉鎮 西鄉鎮,寶安區,深圳市,廣東省 009 007 龍華鎮 廣東省,深圳市,寶安區,龍華鎮 龍華鎮,寶安區,深圳市,廣東省 010 007 松崗鎮 廣東省,深圳市,寶安區,松崗鎮 松崗鎮,寶安區,深圳市,廣東省 (所影響的行數為 10 行) */