Added date and modified date for Oracle table audit

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-08 04:39:35

问题


According to requirenments I need to support two mandatory columns for each table: ADDED_DATE, MODIFIED_DATE.
These are intended for DBA/auditing purposes.

Is it possible to make this stuff totally automatic, implicitly supported by DB itself when I'm inserting / updating records from within application?


回答1:


create a trigger on the table (before update for each row).

SQL> create table foo (hi varchar2(10), added_date date, modified_date date);

Table created.

SQL> create trigger foo_auifer
  2  before update or insert on foo
  3  for each row
  4  declare
  5  begin
  6    if (inserting) then
  7      :new.added_date := sysdate;
  8    elsif (updating) then
  9      :new.modified_date := sysdate;
 10    end if;
 11  end;
 12  /

Trigger created.

SQL> insert into foo (hi) values ('TEST');

1 row created.

SQL> insert into foo (hi) values ('TEST2');

1 row created.

SQL> update foo set hi = 'MODDED' where rownum  = 1;

1 row updated.

SQL> alter session set nls_date_format='dd-mon-yyyy hh24:mi:ss';

Session altered.

SQL> select * from foo;

HI         ADDED_DATE           MODIFIED_DATE
---------- -------------------- --------------------
MODDED     07-nov-2012 15:28:28 07-nov-2012 15:28:39
TEST2      07-nov-2012 15:28:30

SQL>



回答2:


create table "db_user"."my_table" (
    ...
    "added_date" date default sysdate,
    "modified_date" date default sysdate
)
/
create or replace
trigger "db_user"."trg_my_table_audit" 
before update on my_table for each row 
begin 
    :new.modified_date := sysdate;
end;


来源:https://stackoverflow.com/questions/13272711/added-date-and-modified-date-for-oracle-table-audit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!