INSERT INTO SELECT语句与SELECT INTO FROM语句,都是将一个结果集插入到一个表中;
#INSERT INTO SELECT语句
1、语法形式:
Insert into Table2(field1,field2,…) select value1,value2,… from Table1
或
Insert into Table2 select * from Table1
2、限定条件:
(1)Table2必须存在,并且字段field,field2…也必须存在;
(2)如果Table2有主键而且不为空,并且没有设置自增长,则 field1, field2…中必须包括主键;
(3)不要和插入一条数据的sql混了,不要写成:
Insert into Table2(field1,field2,…) values (select value1,value2,… from Table1)
(4)field与value的数据类型要对应上;
3、sql示例:
--1、创建测试表
CREATE TABLE Table_1(
[name_1] [nchar](10) NULL,
[age_1] [int] NULL
)
CREATE TABLE Table_2(
[name_2] [nchar](10) NULL,
[age_2] [int] NULL
) --2、添加测试数据
Insert into Table_1 values('Jack',20)
Insert into Table_1 values('Lily',25) --3、复制表数据部分列和常值
Insert into Table_2(name_2,age_2) select name_1,25 from Table_1
--或
Insert into Table_2 select * from Table_1
#SELECT INTO FROM语句
1、语法形式:
SELECT value1, value2 into Table_2 from Table_1
2、限定条件:
(1)要求目标表Table_2不存在,因为在插入时会自动创建表Table_2;
3、sql示例:
select name,age into Table_3 from Table_2
4、注意:
如果在sql/plus或者PL/SQL执行这条语句,会报”ORA-00905:缺失关键字”错误,原因是PL-SQL与T-SQL的区别。
T-SQL中该句正常,但PL/SQL中解释是:
select..into is part of PL/SQL language which means you have to use it inside a PL/SQL block. You can not use it in a SQL statement outside of PL/SQL.
即不能单独作为一条sql语句执行,一般在PL/SQL程序块(block)中使用。
如果想在PL/SQL中实现该功能,可使用 : Create table newTable as select * from oldTable;
--1. 复制表结构及其数据:
create table new_table as select * from old_table
--2. 只复制表结构:
create table new_table as select * from old_table where 1=2;
--或者:
create table new_table like old_table
表new_table除了没有键,其他的和表old_table一样;
5、应用场景:
(1)SELECT INTO 语句常用于创建表的备份复件或者用于对记录进行存档。
(2)把查询的结果集插入到新表;
#参考:
https://blog.****.net/weixin_39415084/article/details/76170240