LoginSignup
10
6

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;
10
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
10
6