一、区别解释
1、select into from :将查询出来的数据整理到一张新表中保存,表结构与查询结构一致。
select *(查询出来的结果) into newtable(新的表名)from where (后续条件)
即,查询出来结果—>复制一张同结构的空表—>将数据拷贝进去。
2、insert into select :为已经存在的表批量添加新数据。
insert into (准备好的表) select *(或者取用自己想要的结构)from 表名 where 各种条件
即,指定一张想要插入数据的表格—>对数据进行加工筛选—>填入一张准备好的表格。
二、举例详解
select into from 和 insert into select 都是用来复制表
两者的主要区别为: select into from 要求目标表不存在,因为在插入时会自动创建;insert into select from 要求目标表存在。
- 复制表结构及其数据:
create table table_name_new as select * from table_name_old
- 只复制表结构:
create table table_name_new as select * from table_name_old where 1=2;
或者:
create table table_name_new like table_name_old
- 只复制表数据:
如果两个表结构一样:
insert into table_name_new select * from table_name_old
如果两个表结构不一样:
insert into table_name_new(column1,column2...) select column1,column2... from table_name_old
注意事项:
select into 只能用于创建新表,而 insert into select 可以用于向已存在的表中插入数据。
select into 会自动创建新表,如果新表已存在,会报错。而 insert into select 不会创建表,只会向现有表中添加数据。
在使用 insert into select 时,可以选择性地插入数据,通过 where 子句过滤数据,或者使用 order by 对数据进行排序。
在使用 select into 时,如果选择的列与新表中的列不完全匹配,sql server 会自动创建列,但可能会丢失数据类型和约束。
总结
到此这篇关于select into from和insert into select的区别的文章就介绍到这了,更多相关select into from和insert into select区别内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论