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
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