当前位置: 移动技术网 > IT编程>数据库>MSSQL > select into 和 insert into select 两种表复制语句

select into 和 insert into select 两种表复制语句

2017年12月12日  | 移动技术网IT编程  | 我要评论

sbs高清直播,女子溺水男友离开,天命悍匪

第一句:select * into [totable] from [fromtable]
第二句:insert into [totable] ([fild_one],[fild_two]) select [fild_one], 8 from [fromtable]

以上两句都是将 [fromtable] 的数据插入到 [totable],但两句又有区别的:

第一句(select into from)要求目标表[totable]不存在,因为在插入时会自动创建。
第二句(insert into select from)要求目标表[totable]存在,由于目标表已经存在,所以我们除了插入源表[fromtable]的字段外,还可以插入常量,如例中的:8。

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的字段外,还可以插入常量。示例如下:

--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中。示例如下:

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网