【问题标题】:Can we update a record in a table and simultaneously insert the updated record in another table in Oracle DB 11g我们可以在 Oracle DB 11g 中更新表中的记录并同时将更新的记录插入到另一个表中吗
【发布时间】:2018-11-05 15:19:52
【问题描述】:

我想编写一个查询来检查表 A 中的条件并更新与表 A 中的条件匹配的所有记录,然后仅获取这些更新的记录并将它们作为新记录插入表 B 中。表 A 和表 B 两者具有相同的结构。 我尝试使用 Merge 语句执行此操作,但它只满足我的前半部分要求,即更新记录。 请帮忙!

【问题讨论】:

标签: sql oracle oracle11g


【解决方案1】:

执行此操作的一个选项可能是数据库触发器 - 与您对表所做的审计 更改非常相似。例如(基于 Scott 的模式):

SQL> alter session set nls_date_format = 'dd.mm.yyyy hh24:mi:ss';

Session altered.

SQL> create table dept_audit as select * from dept where 1 = 2;

Table created.

SQL> alter table dept_audit add datum date;

Table altered.

SQL> create or replace trigger trg_bu_dept
  2    after update on dept
  3    for each row
  4  begin
  5    insert into dept_audit (deptno, dname, loc, datum)
  6      values (:new.deptno, :new.dname, :new.loc, sysdate);
  7  end;
  8  /

Trigger created.

SQL> update dept set loc = 'Dallas' where deptno = 20;

1 row updated.

SQL> select * from dept_audit;

    DEPTNO DNAME          LOC           DATUM
---------- -------------- ------------- -------------------
        20 RESEARCH       Dallas        05.11.2018 08:19:06

SQL>

所以,您只需要 UPDATE 行;触发器会将它们“复制”到另一个表中。这并不是您在问题中提到的严格意义上的“一个查询”,但 - 希望 - 能够达到目的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2017-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多