11
6

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 5 years have passed since last update.

PL/pgSQLのtriggerでNEW, OLDを透過的に参照する

Posted at

triggerされた行を参照する

PL/pgSQLでは、INSERTの場合は元となった行はNEWで、DELETEの場合はOLDで、UPDATEの場合はNEW/OLDで参照します。

IF TG_OP = 'INSERT' OR 'UPDATE' THEN
  raise notice 'user_id: %', NEW.user_id;
ELSE
  raise notice 'user_id: %', OLD.user_id;
END IF;

参照するカラムが同じ場合は、一旦rowtype型の変数に代入すると、以降のコードを共通化できます。

DECLARE
  source_rec users%rowtype;
BEGIN
  IF TG_OP = 'DELETE' THEN
    source_rec := OLD;
  ELSE
    source_rec := NEW;
  END IF;
  
  raise notice 'user_id: %', source_rec.user_id;
11
6
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
11
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?