SQL语句复制父子级表数据

原始表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

 

转载于:https://www.cnblogs.com/kandyvip/p/6489805.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值