怎样用sql语句复制表table1到表table2的同时复制主键
来源:互联网 发布:2017网络电影大全 编辑:程序博客网 时间:2024/05/16 05:07
在从table1表复制到table2的时候,我们会用语句:
select * into table2 from table1
但这个语句并不能在复制数据的同时,复制主键。
下面的代码通过动态语句,来实现在复制数据的同时,也会复制主键:
if OBJECT_ID('table1') is not null drop table table1gocreate table table1(id int ,idd int,vvv varchar(100),primary key (id,idd) --为了实验在主键有多个字段的情况,所有主键这里有2个字段)insert into table1select 1,1,'a' union allselect 1,2,'b' union allselect 2,1,'a' godeclare @old_table_name varchar(30)declare @new_table_name varchar(30)declare @is_clustered varchar(10)declare @sql varchar(1000)set @old_table_name = 'table1';set @new_table_name = 'table2';set @is_clustered = '';set @sql = '';select @is_clustered = i.type_desc, @sql = @sql + ',' + c.name + case when ic.is_descending_key = 0 then ' asc' else ' desc' end from sys.tables tinner join sys.indexes i on t.object_id = i.object_idinner join sys.index_columns ic on i.object_id = ic.object_id and i.index_id = ic.index_idinner join sys.columns c on c.column_id = ic.column_id and c.object_id = ic.object_idwhere i.is_primary_key = 1 and t.name = @old_table_nameorder by key_ordinalselect @sql = 'if object_id(''' + @new_table_name + ''') is not null' + ' drop table ' + @new_table_name +';' + 'select * into ' + @new_table_name + ' from ' + @old_table_name + ';' + 'alter table ' + @new_table_name + ' add primary key ' + @is_clustered + '(' + stuff(@sql,1,1,'') + ')'select @sql /*if object_id('table2') is not null drop table table2;select * into table2 from table1;alter table table2 add primary key CLUSTERED(id asc,idd asc)*/ exec(@sql)select *from table2/*ididdvvv11a12b21a*/
- 怎样用sql语句复制表table1到表table2的同时复制主键
- 复制表的(create table table1 as select * from table2 )问题
- 将从表table2中查询到的数据插入到已建立的表table1
- 复制表的SQL语句
- 左.右连接相关 , 将table1中数据导入到table2中(表结构不相同)
- SQL语句复制表
- SQL语句 复制表
- sql语句复制表
- SQL语句复制表
- SQL语句复制表
- oracle复制表的sql语句
- SQL语句复制表的方法
- SQL语句复制表的方法
- SQL语句复制表的方法
- oracle复制表的sql语句
- SQL语句复制表的方法
- Oracle复制表的sql语句
- oracle复制表的sql语句
- 大学应设置怎样的计算机专业?
- VMware安装失败 “Failed to create the requested registry key Key:installer Error:1021" .
- JAVA NIO 内存映射文件原理与DirectMemory
- TinyXml快速入门
- IOS打包ipa供异步调试
- 怎样用sql语句复制表table1到表table2的同时复制主键
- CWnd与HWND的区别与转换
- android json解析及简单例子_【未验证】
- android根据density自动放大网络图片
- LevelListDrawable学习
- ubuntu eclipse 不能跳转到标准库头文件
- OpenCV参考手册之Mat类详解(一)
- APEX 调用外部的RESTful Service
- 彩票