1. insert into select 语句

-- 方法一
Insert into Table2(field1,field2,) select value1,value2,from Table1
-- 方法二
Insert into Table2 select * from Table1
-- 方法三
Insert into Table2 select * from Table1 where 条件
1.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的数据类型要对应上;
1.3 实例
-- 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

2. select into from 语句

-- 方式一
SELECT value1, value2 into Table_2 from Table_1;
-- 方拾二
SELECT * into Table_2 from Table_1
-- 方式三 
SELECT * into Table_2 from Table_1 where 条件
2.1 限制条件
  • (1)要求目标表Table_2不存在,因为在插入时会自动创建表Table_2;
2.2 sql示例:
select name,age into Table_3 from  Table_2

3. 注意事项

​   如果在Oracle数据库中执行这条语句,会报”ORA-00905:缺失关键字”错误,原因是数据库的区别。

如果想在Oracle中实现该功能,可使用 :

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

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐