----------------建表-----------------------
 1 create table location
 2 (
 3 id bigint,
 4 pid bigint,
 5 name nvarchar(50)
 6 )
 7 go
 8 insert location
 9 select 001,0,'北京市'
10 union all
11 select 002,001,'海淀区'
12 union all
13 select 003,001,'朝阳区'
14 union all
15 select 004,0,'湖南省'
16 union all
17 select 005,004,'长沙市'
18 union all
19 select 006,004,'株洲市'
20 union all
21 select 007,0,'广东省'
22 union all
23 select 008,007,'广州市'
24 union all
25 select 009,007,'深圳市'
26 go
27 select * from location
28 go

 

--查询指定节点及其所有子节点的函数
 1 create function f_cid(@ID varchar(3)) returns @t_level table(id bigint , level int)
 2 as
 3 begin
 4   declare @level int
 5   set @level = 1
 6   insert into @t_level select @ID , @level
 7   while @@ROWCOUNT > 0
 8   begin
 9     set @level = @level + 1
10     insert into @t_level select a.id , @level
11     from location a , @t_Level b
12     where a.pid = b.id and b.level = @level - 1
13   end
14   return
15 end
16 go
17 select * from dbo.f_cid(007as f 
18 inner join location as t
19 on f.id=t.id
20 go

 

相关文章: