1 create table tb(id varchar(3) , pid varchar(3) , name varchar(10)) 2 insert into tb values('001' , null , '廣東省') 3 insert into tb values('002' , '001' , '廣州市') 4 insert into tb values('003' , '001' , '深圳市') 5 insert into tb values('004' , '002' , '天河區') 6 insert into tb values('005' , '003' , '羅湖區') 7 insert into tb values('006' , '003' , '福田區') 8 insert into tb values('007' , '003' , '寶安區') 9 insert into tb values('008' , '007' , '西鄉鎮') 10 insert into tb values('009' , '007' , '龍華鎮') 11 insert into tb values('010' , '007' , '鬆崗鎮') 12 go 13 --查詢ID = '009'的全部父節點 14 SET @ID = '009' 15 ;WITH T AS 16 ( 17 SELECT ID , PID , NAME 18 FROM TB 19 WHERE ID = @ID 20 UNION ALL 21 SELECT A.ID , A.PID , A.NAME 22 FROM TB AS A JOIN T AS B ON A.ID = B.PID 23 ) 24 SELECT * FROM T ORDER BY ID 25 /* 26 ID PID NAME 27 ---- ---- ---------- 28 NULL 廣東省 29 001 深圳市 30 003 寶安區 31 007 龍華鎮 32 --查詢各節點的父路徑函數(從父到子) 33 create function f_pid1(@id varchar(3)) returns varchar(100) 34 as 35 begin 36 declare @re_str as varchar(100) 37 set @re_str = '' 38 select @re_str = name from tb where id = @id 39 while exists (select 1 from tb where id = @id and pid is not null) 40 begin 41 select @id = b.id , @re_str = b.name + ',' + @re_str from tb a , tb b where a.id = @id and a.pid = b.id 42 end 43 return @re_str 44 end 45 go 46 --查詢各節點的父路徑函數(從子到父) 47 create function f_pid2(@id varchar(3)) returns varchar(100) 48 as 49 begin 50 declare @re_str as varchar(100) 51 set @re_str = '' 52 select @re_str = name from tb where id = @id 53 while exists (select 1 from tb where id = @id and pid is not null) 54 begin 55 select @id = b.id , @re_str = @re_str + ',' + b.name from tb a , tb b where a.id = @id and a.pid = b.id 56 end 57 return @re_str 58 end 59 go 60 61 select * , 62 dbo.f_pid1(id) [路徑(從父到子)] , 63 dbo.f_pid2(id) [路徑(從子到父)] 64 from tb order by id 65 66 drop function f_pid1 , f_pid2 67 drop table tb 68 69 /* 70 id pid name 路徑(從父到子) 路徑(從子到父) 71 ---- ---- ------ --------------------------- ---------------------------- 72 NULL 廣東省 廣東省 廣東省 73 001 廣州市 廣東省,廣州市 廣州市,廣東省 74 001 深圳市 廣東省,深圳市 深圳市,廣東省 75 002 天河區 廣東省,廣州市,天河區 天河區,廣州市,廣東省 76 003 羅湖區 廣東省,深圳市,羅湖區 羅湖區,深圳市,廣東省 77 003 福田區 廣東省,深圳市,福田區 福田區,深圳市,廣東省 78 003 寶安區 廣東省,深圳市,寶安區 寶安區,深圳市,廣東省 79 007 西鄉鎮 廣東省,深圳市,寶安區,西鄉鎮 西鄉鎮,寶安區,深圳市,廣東省 80 007 龍華鎮 廣東省,深圳市,寶安區,龍華鎮 龍華鎮,寶安區,深圳市,廣東省 81 007 鬆崗鎮 廣東省,深圳市,寶安區,鬆崗鎮 鬆崗鎮,寶安區,深圳市,廣東省 82 83 (所影響的行數爲 10 行) 84 */