您的位置:首页 > 其它

树形结构的处理--数据复制

2009-01-08 10:53 363 查看
--数据结构

表名tb,如果修改表名,则相应修改所有数据处理中涉及到的表名tb

id为编号(标识字段+主键)

pid为上级编号

name为名称,后面可以自行增加其他字段.

/*--数据复制

如果表中包含自定义字段,需要修改存储过程

存在嵌套不超过32层的问题.

--*/

--创建复制的存储过程--复制指定结点下的子结点到另一个结点下

create proc p_copy

@s_id int, --复制该项下的所有子项

@d_id int, --复制到此项下

@new_id int --新增加项的开始编号

as

declare @nid int,@oid int,@name varchar(20)

select id,name into #temp from tb where pid=@s_id and id<@new_id

while exists(select 1 from #temp)

begin

select @oid=id,@name=name from #temp

insert into tb values(@d_id,@name)

set @nid=@@identity

exec p_copy @oid,@nid,@new_id

delete from #temp where id=@oid

end

go

--创建批量复制的存储过程--复制指定结点及其下面的所有子结点,并生成新结点

create proc p_copystr

@s_id varchar(8000) --要复制项的列表,用逗号分隔

as

declare @nid int,@oid int,@name varchar(20)

set @s_id=','+@s_id+','

select id,name into #temp from tb

where charindex(','+cast(id as varchar)+',', @s_id)>0

while exists(select 1 from #temp)

begin

select @oid=id,@name=name from #temp

insert into tb values(@oid,@name)

set @nid=@@identity

exec p_copy @oid,@nid,@nid

delete from #temp where id=@oid

end

go

--测试

exec p_copystr '5,6'

--显示处理结果

select * from tb order by dbo.f_getmergid(id)

go
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: