我的主要思路是这样的有一个树形结构的表。比如编码,父级编码,级次,是否叶子id pid level leaf A null 1 0 B A 2 0 C B 3 1 D A 2 1 E null 1 0 F E 2 1 G E 2 1我想要这样的数据,以A为例 order pid id plevel level leaf 001 null A 0 1 0 001 A A 1 1 0 001001 A B 1 2 0 001001001 A C 1 3 1 001002 A D 1 2 1 每个节点都要构造 父级为null的一条记录 父级是本身的记录 所有下级节点的记录用了递归调用,可不好使!
下面是一个简单的递归调用,请各位看看。明显的存储过程不支持。如果我写法有误请指点! drop table tb create table tb(id varchar(10),name varchar(10),pid varchar(10)) insert into tb select '001','一级一',null union all select '00101','二级一','001' union all select '00102','二级二','001' union all select '00103','二级三','001' union all select '0010201','三级一','00102' union all select '0010202','三级三','00102' select * from tb drop proc prc_test go create procedure prc_test @pid varchar(10) as begin if object_id('t') is null create table t(pid varchar(10),cid varchar(10)) declare @id varchar(10) if @pid is null declare cur cursor for select id from tb where pid is null else declare cur cursor for select id from tb where pid=@pid
open cur fetch cur into @id while @@fetch_status=0 begin insert into t values (@pid,@id) exec prc_test @id fetch cur into @id end close cur deallocate cur end /* 提示信息 无法在 sysdepends 中添加当前存储过程所对应的行,因为缺少该存储过程所依赖的对象 'prc_test'。仍将创建该存储过程。 */ exec prc_test null /*执行时提示(所影响的行数为 1 行)服务器: 消息 16915,级别 16,状态 1,过程 prc_test,行 12 名为 'cur' 的游标已存在。 服务器: 消息 16905,级别 16,状态 1,过程 prc_test,行 14 游标已打开。 服务器: 消息 16916,级别 16,状态 1,过程 prc_test,行 20 名为 'cur' 的游标不存在。 服务器: 消息 16916,级别 16,状态 1,过程 prc_test,行 22 名为 'cur' 的游标不存在。 服务器: 消息 16916,级别 16,状态 1,过程 prc_test,行 23 名为 'cur' 的游标不存在。 */
A null 1 0
B A 2 0
C B 3 1
D A 2 1
E null 1 0
F E 2 1
G E 2 1我想要这样的数据,以A为例
order pid id plevel level leaf
001 null A 0 1 0
001 A A 1 1 0
001001 A B 1 2 0
001001001 A C 1 3 1
001002 A D 1 2 1
每个节点都要构造
父级为null的一条记录
父级是本身的记录
所有下级节点的记录用了递归调用,可不好使!
drop table tb
create table tb(id varchar(10),name varchar(10),pid varchar(10))
insert into tb
select '001','一级一',null union all
select '00101','二级一','001' union all
select '00102','二级二','001' union all
select '00103','二级三','001' union all
select '0010201','三级一','00102' union all
select '0010202','三级三','00102' select * from tb
drop proc prc_test
go
create procedure prc_test @pid varchar(10)
as
begin
if object_id('t') is null
create table t(pid varchar(10),cid varchar(10)) declare @id varchar(10) if @pid is null
declare cur cursor for select id from tb where pid is null
else
declare cur cursor for select id from tb where pid=@pid
open cur
fetch cur into @id
while @@fetch_status=0
begin
insert into t values (@pid,@id)
exec prc_test @id
fetch cur into @id
end
close cur
deallocate cur
end
/*
提示信息
无法在 sysdepends 中添加当前存储过程所对应的行,因为缺少该存储过程所依赖的对象 'prc_test'。仍将创建该存储过程。
*/
exec prc_test null
/*执行时提示(所影响的行数为 1 行)服务器: 消息 16915,级别 16,状态 1,过程 prc_test,行 12
名为 'cur' 的游标已存在。
服务器: 消息 16905,级别 16,状态 1,过程 prc_test,行 14
游标已打开。
服务器: 消息 16916,级别 16,状态 1,过程 prc_test,行 20
名为 'cur' 的游标不存在。
服务器: 消息 16916,级别 16,状态 1,过程 prc_test,行 22
名为 'cur' 的游标不存在。
服务器: 消息 16916,级别 16,状态 1,过程 prc_test,行 23
名为 'cur' 的游标不存在。
*/