【问题标题】:COPY MULTIPLE ROW which has DATA from one table to another table where columns are same in each row. OracleCOPY MULTIPLE ROW 将数据从一个表复制到另一个表,其中每一行的列相同。甲骨文
【发布时间】:2022-01-18 15:47:13
【问题描述】:

我想将多行数据从一个表复制到另一个表,其中每个表中的列都相同。

我知道 INSERT INTO 但是有更简单的方法吗?

我该怎么做?

这是我的示例表:

DROP TABLE table1;
CREATE TABLE table1(
    firstname VARCHAR(10),
    lastname  VARCHAR(10)
);

INSERT INTO table1 (firstname, lastname)
VALUES('John1', 'Peterson1');

INSERT INTO table1 (firstname, lastname)
VALUES('John2', 'Peterson2');

INSERT INTO table1 (firstname, lastname)
VALUES('John3', 'Peterson3');

INSERT INTO table1 (firstname, lastname)
VALUES('John4', 'Peterson4');

DROP TABLE table2;
CREATE TABLE table2(
    firstname VARCHAR(10),
    lastname  VARCHAR(10),
    AGE VARCHAR(10)
);

提前致谢(使用 Oracle)

【问题讨论】:

  • 不要存储age。如果某人今天 10 岁,那么明天可能会过时,因为他们可能 11 岁,而且肯定会在一年后过时。如果您想知道年龄,请存储date_of_birth 并计算他们的年龄。

标签: sql oracle oracle11g


【解决方案1】:

更简单的方法称为CTAS (Create Table As Select)。

create table table2 as
select * from table1;

你说:

...每个表中的 WHERE 列都相同。

很抱歉通知您,但是 - 在您的示例中,table1table2 是不同的。

在这种情况下,您需要设置列名:

create table table2 as
select firstname, lastname, cast(null as varchar2(10)) age
from table1;

顺便说一句,如果它的数据类型是varchar2(10),它是什么样的“年龄”?我虽然年龄以年为单位(number 数据类型)...


[演示]

SQL> select * from table1;

FIRSTNAME  LASTNAME
---------- ----------
John1      Peterson1
John2      Peterson2
John3      Peterson3
John4      Peterson4

SQL> create table table2 as
  2  select firstname, lastname, cast(null as varchar2(10)) age
  3  from table1;

Table created.

SQL> select * from table2;

FIRSTNAME  LASTNAME   AGE
---------- ---------- ----------
John1      Peterson1
John2      Peterson2
John3      Peterson3
John4      Peterson4

SQL> desc table2
 Name                    Null?    Type
 ----------------------- -------- ----------------
 FIRSTNAME                        VARCHAR2(10)
 LASTNAME                         VARCHAR2(10)
 AGE                              VARCHAR2(10)

SQL>

【讨论】:

  • 哦,是的。我的错。应该是年龄,所以是一个数字
  • 好的;所以把它转换成一个数字,然后。
  • 是否将 table1 中的行中的数据插入到 table2 中,使用创建表 table2 作为 select firstname, lastname, cast(null as varchar2(10)) age from table1;?
  • 是的;这就是 CTAS 的重点。
  • 我不断收到此错误 ORA-00923: FROM keyword not found where expected when I try to run create table table2 as select firstname, lastname, cast(null as varchar2(10)) age from table1;但是从我的表中插入的值
猜你喜欢
  • 2012-11-24
  • 2023-03-16
  • 2020-11-03
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
相关资源
最近更新 更多