前提
このようにテーブルに1行レコードが挿入されているとする。
テーブル名:test_automatic_updating
id | name | created_at | updated_at |
---|---|---|---|
1 | makima | 2023 06:50:20 | 2023 06:50:20 |
やり方
①関数を定義
②トリガーを定義
①関数を定義
CREATE FUNCTION update_test_automatic_updating_updated_at()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
②トリガーを定義
CREATE TRIGGER update_test_automatic_updating
BEFORE UPDATE ON test_automatic_updating
FOR EACH ROW
EXECUTE FUNCTION update_test_automatic_updating_updated_at();
テーブルを更新
-- 名前だけ変更
UPDATE test_automatic_updating SET name = 'shihainoakuma' ;
結果、update_atの値も更新してくれている
id | name | created_at | updated_at |
---|---|---|---|
1 | shihainoakuma | 2023 06:50:20 | 2023 07:00:21 |