postgres 单表触发器

表结构

CREATE TABLE "test_trigger" (
  "id" int4 NOT NULL,
  "x" float8,
  "y" float8,
  "plus" float8,
  CONSTRAINT "test_trigger_pkey" PRIMARY KEY ("id")
)

需求

当x,y字段变化时,更新 plus 字段

创建funtion

CREATE OR REPLACE FUNCTION "update_plus"()
  RETURNS "pg_catalog"."trigger" AS $BODY$ BEGIN
        NEW."plus" := NEW.x+NEW.y;
    RETURN NEW;
    
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100

创建触发器

CREATE TRIGGER "trigger_plus" BEFORE INSERT OR UPDATE OF "x", "y" ON "test_trigger"
FOR EACH ROW
EXECUTE PROCEDURE "update_plus"();

注意上面的 UPDATE OF "x", "y" 标识只有当x、y变化时,才会执行此触发器

你可能感兴趣的:(postgresql,sql,trigger)