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
一、INSERT INTO SELECT語句
1、語句形式為:
Insert into Table2(field1,field2,...) select value1,value2,... from Table1
2、注意地方:
(1)要求目標表Table2必須存在,並且字段field,field2...也必須存在
(2)注意Table2的主鍵約束,如果Table2有主鍵而且不為空,則 field1, field2...中必須包括主鍵
(3)注意語法,不要加values,和插入一條數據的sql混了,不要寫成:
Insert into Table2(field1,field2,...) values (select value1,value2,... from Table1)
(4)由於目標表Table2已經存在,所以我們除了插入源表Table1的字段外,還可以插入常量。
--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',null)
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
二、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',null)
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