简体   繁体   English

将记录从一个 Oracle SQL 表复制到另一个具有额外列的表

[英]Copy record from one Oracle SQL table to another with extra columns

This is part of a larger Java program, but I'm looking for a way in Oracle SQL to copy a record from one table to another.这是较大的 Java 程序的一部分,但我正在 Oracle SQL 中寻找一种将记录从一个表复制到另一个表的方法。 The original table is 45 columns.原始表为 45 列。 The second table is an archive table of the original table.第二个表是原始表的存档表。

EDIT - It has the same 45 columns, but also has a NewKey column - created in the archive table using编辑 - 它有相同的 45 列,但也有一个 NewKey 列 - 在存档表中创建使用

("NEWKEY" NUMBER GENERATED ALWAYS as IDENTITY(START with 1 INCREMENT by 1)

and an archive_date column和一个 archive_date 列

"ARCHIVEDATE" DATE DEFAULT CURRENT_TIMESTAMP

Is there a way to do a query a la有没有办法做一个查询

INSERT INTO Archive_Table A
SELECT * (plus NEWKEY, ARCHIVEDATE) FROM Original Table O
WHERE O.CUSTKEY = passed_param;

where the only parameter passed is the CUSTKEY?传递的唯一参数是 CUSTKEY? Once a record is copied from the original table, it will then be deleted from the original table.一旦从原始表中复制了一条记录,它将从原始表中删除。

ARCHIVEDATE is a date field, so it should default to SYSDATE, not CURRENT_TIMESTAMP. ARCHIVEDATE 是一个日期字段,所以它应该默认为 SYSDATE,而不是 CURRENT_TIMESTAMP。 This eliminates a conversion for every insert.这消除了每个插入的转换。

As others have said, just list out the columns:正如其他人所说,只需列出列:

insert into archivetable (custkey, cola, colb, colc) 
select custkey, cola, colb, colc 
  from originaltable 
 where custkey = passedparam;

There is no need to include NEWKEY or ARCHIVEDATE as they will be initialized on the insert.无需包含 NEWKEY 或 ARCHIVEDATE,因为它们将在插入时被初始化。

If you started typing those 45 columns half an hour ago (when you posted the question), your code would have already be up and running.如果您在半小时前(当您发布问题时)开始输入这 45 列,那么您的代码就已经启动并运行了。

Anyway: using an asterisk ( * ) in select is probably not the best idea;无论如何:在select中使用星号 ( * ) 可能不是最好的主意; for what?为了什么? What benefit do you expect?你期望什么好处? To save some keyboard strokes?为了节省一些键盘敲击? Because, if you explicitly name all columns, you exactly know which value goes into which column.因为,如果您明确命名所有列,您就确切地知道哪个值进入哪个列。 What if a new column is added into one of those two tables?如果在这两个表之一中添加一个新列怎么办? insert into select * won't work any longer. insert into select *将不再起作用。

What you ask can be done using some dynamic SQL (so, within PL/SQL) by querying user_tab_columns , composing the insert into statement, paying attention to differences (identity and timestamp columns).您可以使用一些动态 SQL (因此,在 PL/SQL 中)通过查询user_tab_columns来完成您的要求,将insert into语句组合在一起,注意差异(身份和时间戳列)。 Once you're done with coding and testing, as I said - a straightforward naming all those columns would be finished ages ago.一旦你完成了编码和测试,正如我所说的 - 一个简单的命名所有这些列将在很久以前完成。

If I were you, I'd do exactly that: name all 45 columns.如果我是你,我会这样做:命名所有 45 列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM