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_cid(@ID varchar(3)) returns @t_level table(id varchar(3) , level int)asbegin declare @level int set @level = 1 insert into @t_level select @id , @level while @@ROWCOUNT > 0 begin set @level = @level + 1 insert into @t_level select a.id , @level from tb a , @t_Level b where a.pid = b.id and b.level = @level - 1 end returnendgo --調用函數查詢001(廣東省)及其所有子節點select a.* from tb a , f_cid('001') b where a.id = b.id order by a.id/*id pid name ---- ---- ---------- 001 NULL 廣東省002 001 廣州市003 001 深圳市004 002 天河區005 003 羅湖區006 003 福田區007 003 寶安區008 007 西鄉鎮009 007 龍華鎮010 007 松崗鎮 (所影響的行數為 10 行)*/ --調用函數查詢002(廣州市)及其所有子節點select a.* from tb a , f_cid('002') b where a.id = b.id order by a.id/*id pid name ---- ---- ---------- 002 001 廣州市004 002 天河區 (所影響的行數為 2 行)*/ --調用函數查詢003(深圳市)及其所有子節點select a.* from tb a , f_cid('003') b where a.id = b.id order by a.id/*id pid name ---- ---- ---------- 003 001 深圳市005 003 羅湖區006 003 福田區007 003 寶安區008 007 西鄉鎮009 007 龍華鎮010 007 松崗鎮 (所影響的行數為 7 行)*/ drop table tbdrop function f_cid