您的位置:首页 > 数据库

SQL语句复制父子级表数据

2017-03-02 11:45 274 查看
原始表Book数据如下: id为自增长整数,text为内容,pid为上级ID
id text pid
1 第一层 0
2 数学 0
3 第二层 1
4 语文 1
5 第三层 3
6 英语 3
……………………

现要求拷贝一份这样的数据到同一个表Book中,成功后的数据应该如下
id text pid
100 第一层 0
101 数学 0
102 第二层 100
103 语文 100
104 第三层 102
105 英语 102

……………………

--第一步:复制全部数据
Insert Into Book(text,pid) Select a.text,a.pid From Book a where 条件

--第二步:创建变量表
declare @t table(idx int,id int,pid int,id2 int,pid2 int)
Insert Into @t
select ROW_NUMBER() OVER (ORDER BY a.pid) AS idx,a.id,a.pid,b.id id2,b.pid pid2
from Book a inner join Book b on b.text=a.text and b.pid=a.pid where 条件

--第三步:修改新数据的pid
update Book set pid=c.id2
from @t a
inner join @t b on b.pid=a.id
inner join @t c on c.idx=a.idx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: