Insert是T-sql中常用語句,Insert INTO table(field1,field2,...) values(value1,value2,...)這種形式的在應用程序開發中必不可少。但我們在開發、測試過程中,經常會遇到需要表複製的情況,如將一個table1的數據的部分字段複製到table2中,或者將整個table1複製到table2中,這時候我們就要使用SELECT INTO 和 INSERT INTO SELECT 表複製語句了。
1.INSERT INTO SELECT語句
語句形式為:Insert into Table2(field1,field2,...) select value1,value2,... from Table1
要求目標表Table2必須存在,由於目標表Table2已經存在,所以我們除了插入源表Table1的字段外,還可以插入常量。示例如下:
INSERT INTO SELECT語句複製表數據
--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
--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
2.SELECT INTO FROM語句
語句形式為:SELECT vale1, value2 into Table2 from Table1
要求目標表Table2不存在,因為在插入時會自動創建表Table2,並將Table1中指定字段數據複製到Table2中。示例如下:
SELECT INTO FROM創建表並複製表數據
--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
--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