WEB开发网
开发学院数据库MSSQL Server MSSQL 查询所有节点及其所有子节点的函数 阅读

MSSQL 查询所有节点及其所有子节点的函数

 2012-10-29 13:45:01 来源:WEB开发网   
核心提示:e ef fg g(所影响的行数为 7 行)*/--删除测试数据 drop function f_getchild drop table tbSQL code/*标题:查询所有顶级节点及其子节点的例地址:http://www.52mvc.com作者:爱新觉罗&mid
e e
f f
g g


(所影响的行数为 7 行)


*/


--删除测试数据
drop function f_getchild
drop table tb


SQL code
/*
标题:查询所有顶级节点及其子节点的例
地址:http://www.52mvc.com
作者:爱新觉罗·毓华(十八年风雨,守得冰山雪莲花开)
时间:2009-03-23
地点:广东深圳
*/


[code=SQL]create table Area (id int identity,Name varchar(10) ,order_by int ,father_ID int )
insert into area values('广东省',2,0)
insert into area values('四川省',2,0)
insert into area values('湖北省',2,0)
insert into area values('东莞市',1,1)
insert into area values('广州市',1,1)
insert into area values('天河区',0,5)
insert into area values('绵阳市',1,2)
insert into area values('武汉市',1,3)
insert into area values('汉口区',0,8)
insert into area values('随州市',1,3)
go


select * from area


drop table area


/*
id Name order_by father_ID
----------- ---------- ----------- -----------
1 广东省 2 0
2 四川省 2 0
3 湖北省 2 0
4 东莞市 1 1
5 广州市 1 1
6 天河区 0 5
7 绵阳市 1 2
8 武汉市 1 3
9 汉口区 0 8
10 随州市 1 3


(所影响的行数为 10 行)


要求显示为:
name
--------------
广东省
东莞市
广州市
天河区
四川省
绵阳市
湖北省
武汉市
汉口区
随州市


(所影响的行数为 10 行)
*/


SQL code
--创建原始表
create table Area (id int identity,Name varchar(10) ,order_by int ,father_ID int )
insert into area values('广东省',2,0)
insert into area values('四川省',2,0)
insert into area values('湖北省',2,0)
insert into area values('东莞市',1,1)
insert into area values('广州市',1,1)
insert into area values('天河区',0,5)
insert into area values('绵阳市',1,2)
insert into area values('武汉市',1,3)
insert into area values('汉口区',0,8)
insert into area values('随州市',1,3)
--创建临时表
create table tmp (id int identity,Name varchar(10) ,order_by int ,father_ID int )
go


--创建查询指定节点及其所有子节点的函数
create function f_cid(@ID int) returns @t_level table(id int , level int)
as
begin
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 area a , @t_Level b
where a.father_ID = b.id and b.level = @level - 1
end
return
end
go


--创建存储过程并将数据插入临时表
create proc my_proc
as
begin
declare @id as int

Tags:MSSQL 查询 所有

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接