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
……………………
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
相关文章推荐
- 复制数据的Sql语句
- 在SqlServer中如何使用Sql语句将一张表的数据复制到另一张表
- 复制表结构和数据SQL语句
- Sql 语句实现在同一个DB中复制表和空清一个DataTable中的所有数据
- 复制表结构和数据SQL语句
- MySQL复制表结构和数据SQL语句
- 用SQL语句复制数据表
- MySQL复制表结构和表数据的SQL语句和时间函数
- 使用SQL语句的子查询批量复制表数据
- SQL语句:在两个数据库间复制表结构和更新数据
- MySQL复制表结构和数据SQL语句
- SQL语句:在两个数据库间复制表结构和数据数据库
- 创建、删除、修改、复制表结构和复制数据SQL语句
- 复制表结构和数据SQL语句(数据库水平切分)
- 复制表结构和数据SQL语句
- 关于父子级数据的sql复制处理
- MySQL复制表结构和数据SQL语句
- 复制表结构和数据SQL语句
- MySQL复制表结构和数据SQL语句
- 如何用SQL语句复制表和表中的数据?