3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Oracle Database(Oracle APEX)で登録日や更新日の列を機能させる方法(トリガー)

Last updated at Posted at 2023-09-06

image.png

はじめに

表の列にレコードの登録日や更新日を設定したい場面は多いと思いますが、実装に意外に手間取ったので、記録を取りたいと思います。
サンプルデータを作って、実装してみました。

デモデータの準備

create table sample(
    ID number(20),
    first_name varchar2(50),
    last_name varchar2(50),
    salary number(20),
    REGISTER_ON date,
    UPDATE_ON date
    );
insert into sample
    (ID,
    first_name,
    last_name,
    salary) 
VALUES
    (1,'TARO','SUZUKI',1000);

insert into sample
    (ID,
    first_name,
    last_name,
    salary) 
VALUES
    (2,'HANAKO','YAMADA',2000);

insert into sample
    (ID,
    first_name,
    last_name,
    salary) 
VALUES
     (3,'YUKI','YAMADA',1500);
describe sample;

image.png

select * from sample

image.png

以上のようにサンプルデータを用意しました。

image.png

image.png

APEXの画面で見ると以上のようになります。

Register On(登録日)やUpdate ON(更新日)に関しては何もデータ入力していないので、空っぽです。

登録日と更新日を記録する方法

結論から言うと、トリガーを使用します。
以下がトリガー作成のコードです。

create or replace trigger "SAMPLE_TABLE_BIU"
before insert or update on SAMPLE
    for each row
begin

    if inserting then
        :new.register_on :=localtimestamp;
        :new.update_on   :=localtimestamp;
    end if;
    if updating then
        :new.update_on   :=localtimestamp;
    end if;
end;

トリガーは作成するだけでなく有効化しないと発動されないので、有効化まで行います。

ALTER TRIGGER "SAMPLE_TABLE_BIU" ENABLE;

以上で設定が完了しました!
実際に動きを見てみましょう。

結果

ケース①TAROのレコードを更新してみる

現状、TAROのレコードは以下のように登録日、更新日は空っぽになっています

image.png

このレコードを更新してみます。

Salaryを1000から2000に変えてみます。

image.png

そうすると更新日がトリガーの効果で入力されました!

ケース②新規レコードを挿入してみる

image.png

以上の内容の新規レコードを挿入しました

image.png

登録日も更新日もトリガーによって入力されました!

まとめ

レコードの登録日、更新日列の作成方法についてのまとめでした。
頻繁に使えるトリガーコードだと思うので、忘れないようにQiitaで記事を書いてみました。何かの参考になればと思います。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?