oracle数据库如何复制表到新表?

我们经常会遇到需要表复制的情况,如将一个table1的数据的部分字段复制到table2中,或者将整个table1复制到table2中,这时候我们就要使用select into 和 insert into select 表复制语句了。

1.insert into select语句

语句形式为:insert into table2(field1,field2,…) select value1,value2,… from table1

注意:

(1)要求目标表table2必须存在,并且字段field,field2…也必须存在

(2)注意table2的主键约束,如果table2有主键而且不为空,则 field1, field2…中必须包括主键

(3)注意语法,不要加values,和插入一条数据的sql混了,不要写成:

insert into table2(field1,field2,…) values (select value1,value2,… from table1)

由于目标表table2已经存在,所以我们除了插入源表table1的字段外,还可以插入常量。示例如下:

+ expand sourceview plaincopy to clipboardprint

–1.创建测试表

    create table table1  
    (  
        a varchar(10),  
        b varchar(10),  
        c varchar(10)
    )
    create table table2  
    (  
        a varchar(10),  
        c varchar(10),  
        d int
    )

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

select * from table2

–3.insert into select语句复制表数据

insert into table2(a, c, d) select a,c,5 from table1

–4.显示更新后的结果

select * from table2

–5.删除测试表

drop table table1

drop table table2

2.select into from语句

语句形式为:select vale1, value2 into table2 from table1

要求目标表table2不存在,因为在插入时会自动创建表table2,并将table1中指定字段数据复制到table2中。示例如下:

view plaincopy to clipboardprint

–1.创建测试表

create table table1

(

a varchar(10),

b varchar(10),

c varchar(10)

)

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

–3.select into from语句创建表table2并复制数据

select a,c into table2 from table1

–4.显示更新后的结果

select * from table2

–5.删除测试表

drop table table1 点击打开链接

drop table table2

注意:如果在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 …:

如:

create table newtable as select * from atable;

newtable 除了没有键,其他的和atable一样 <

(0)
上一篇 2022年3月22日
下一篇 2022年3月22日

相关推荐