select into from 和 insert into select都是用来复制表,两者的主要区别为: select into from 要求目标表不存在,因为在插入时会自动创建。insert into select from 要求目标表存在
备份表数据: create table emp as select * from scott.emp
还原表数据:insert into emp select * from scott.emp
1. 复制表结构及其数据:
create table table_name_new as select * from table_name_old
2. 只复制表结构:
create table table_name_new as select * from table_name_old where 1=2;
或者:
create table table_name_new like table_name_old
3. 只复制表数据:
如果两个表结构一样:
insert into table_name_new select * from table_name_old
如果两个表结构不一样:
insert into table_name_new(column1,column2...) select column1,column2... from table_name_old
pasting
1.INSERT INTO SELECT语句
语句形式为:Insert into Table2(field1,field2,...) select value1,value2,... from Table1
要求目标表Table2必须存在,由于目标表Table2已经存在,所以我们除了插入源表Table1的字段外,还可以插入常量。示例如下:
(
constraint [pk_users] primary key clustered
( [userid] ASC)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
这是在userid列上创建一个聚集索引的语句。primary key表明创建的是主键约束,culstered表示索引类型是聚集索引,IGNORE_DUP_KEY = OFF的作用是在向表中插入数据的时候,如果遇到表中已经存在userid的值,insert语句就会失败,并且回滚整个insert语句。ON [PRIMARY]表示是索引创建在主文件组上。[pk_users] 是主键的名称。)
--1.创建测试表
create TABLE Table1
(
a varchar(10),
b varchar(10),
c varchar(10),
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
a ASC
)
) ON [PRIMARY]
create TABLE Table2
(
a varchar(10),
c varchar(10),
d int,
CONSTRAINT [PK_Table2] PRIMARY KEY CLUSTERED
(
a ASC
)
) ON [PRIMARY]
GO
--2.创建测试数据
Insert into Table1 values('赵','asds','90')
Insert into Table1 values('钱','asds','100')
Insert into Table1 values('孙','asds','80')
Insert into Table1 values('李','asds',/image/bnVsbA%3D%3D)
GO
select * from Table2
--3.INSERT INTO SELECT语句复制表数据
Insert into Table2(a, c, d) select a,c,5 from Table1
GO
--4.显示更新后的结果
select * from Table2
GO
--5.删除测试表
drop TABLE Table1
drop TABLE Table2
2.SELECT INTO FROM语句
语句形式为:SELECT vale1, value2 into Table2 from Table1
要求目标表Table2不存在,因为在插入时会自动创建表Table2,并将Table1中指定字段数据复制到Table2中。示例如下:
--1.创建测试表
create TABLE Table1
(
a varchar(10),
b varchar(10),
c varchar(10),
CONSTRAINT [PK_Table1] PRIMARY KEY CLUSTERED
(
a ASC
)
) ON [PRIMARY]
GO
--2.创建测试数据
Insert into Table1 values('赵','asds','90')
Insert into Table1 values('钱','asds','100')
Insert into Table1 values('孙','asds','80')
Insert into Table1 values('李','asds',/image/bnVsbA%3D%3D)
GO
--3.SELECT INTO FROM语句创建表Table2并复制数据
select a,c INTO Table2 from Table1
GO
--4.显示更新后的结果
select * from Table2
GO
--5.删除测试表
drop TABLE Table1
drop TABLE Table2