如何更正历史记录

时间:2019-06-07 12:49:00

标签: database oracle

我想更新oracle数据库中的历史记录数据。

emp表

ID      SALE_COM    UPDATEDATE              SALES_DT
4173    40          09-APR-2016 20:04:07    null
4173    40          20-SEP-2016 20:04:11    null
4173    30          06-OCT-2016 20:04:07    null
4173    30          14-OCT-2016 20:04:07    null
4173    30          26-MAR-2017 20:50:41    null

emp_hist

EMP_ID  FIN_Y_ID    PRD_SEQ  FIELD_VALUE    FIN_DATE
2167    13          4        30             28/09/14 0:00

输出

4173    30  06-OCT-2016 20:04:07    28/09/14 0:00

1 个答案:

答案 0 :(得分:0)

我不愿回答这个问题,而没有更清楚地定义问题,但这是我的解释:

  1. 有两个表:emp和emp_hist
  2. 原始帖子中emp_hist中显示的2167不正确,实际上应该是4173
  3. 更新EMP.SALES_COM时,您要从EMP_HIST.FIN_DATE的值更新EMP.SALES_DT,其中EMP.ID = EMP_HIST.EMP_ID

假设EMP_HIST.EMP_ID是唯一的,则可以在执行上述#3的EMP上创建触发器:

SQL> SELECT id, sale_com, TO_CHAR(updatedate, 'DD-MON-YYYY HH24:MI:SS') updatedate,
  2          TO_CHAR(sales_dt, 'DD/MM/YY HH24:MI') sales_dt
  3    FROM emp;

        ID   SALE_COM UPDATEDATE                    SALES_DT      
---------- ---------- ----------------------------- --------------
      4173         40 09-APR-2016 20:04:07                        
      4173         40 20-SEP-2016 20:04:11                        
      4173         30 06-OCT-2016 20:04:07                        
      4173         30 14-OCT-2016 20:04:07                        
      4173         30 26-MAR-2017 20:50:41                        

SQL> SELECT emp_id, FIN_Y_ID, PRD_SEQ, FIELD_VALUE, TO_CHAR(FIN_DATE, 'YY/MM/DD HH24:MI') fin_date
  2    FROM emp_hist;

    EMP_ID   FIN_Y_ID    PRD_SEQ FIELD_VALUE FIN_DATE      
---------- ---------- ---------- ----------- --------------
      4173         13          4          30 14/09/28 00:00

SQL> CREATE OR REPLACE TRIGGER emp_upd_sale_com BEFORE UPDATE ON emp FOR EACH ROW
  2  BEGIN
  3    SELECT fin_date
  4      INTO  :new.sales_dt
  5      FROM emp_hist
  6      WHERE emp_id = :old.id;
  7  END;

Trigger EMP_UPD_SALE_COM compiled

SQL> UPDATE emp SET sale_com = 30
  2    WHERE id = 4173 AND updatedate = TO_DATE('06-OCT-2016 20:04:07', 'DD-MON-YYYY HH24:MI:SS');

1 row updated.

SQL> SELECT id, sale_com, TO_CHAR(updatedate, 'DD-MON-YYYY HH24:MI:SS') updatedate,
  2         TO_CHAR(sales_dt, 'DD/MM/YY HH24:MI') sales_dt
  3    FROM emp;

        ID   SALE_COM UPDATEDATE                    SALES_DT      
---------- ---------- ----------------------------- --------------
      4173         40 09-APR-2016 20:04:07                        
      4173         40 20-SEP-2016 20:04:11                        
      4173         30 06-OCT-2016 20:04:07          28/09/14 00:00 <<<< Updated row
      4173         30 14-OCT-2016 20:04:07                        
      4173         30 26-MAR-2017 20:50:41