在 postgresql 中插入新行时触发更新 table 列?

Trigger to update table column when new row is insert in postgresql?

我想编写触发器以在插入新行时更新 table。我正在使用

之类的更新查询
UPDATE table SET
  geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326) 

我通过写触发器函数解决了

CREATE OR REPLACE FUNCTION function_update()
  RETURNS trigger AS
$BODY$
BEGIN
   new.geom := ST_SetSRID(ST_MakePoint(new.longitude, new.latitude), 4326);

RETURN new;
END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION function_update()
  OWNER TO postgres;

我写了触发器来更新

CREATE TRIGGER triggerinsert
  Before INSERT
  ON rdpr
  FOR EACH ROW
  EXECUTE PROCEDURE function_update();

您需要使用 BEFORE 触发器,然后分配新值:

CREATE OR REPLACE FUNCTION function_update()
  RETURNS trigger AS
$BODY$
BEGIN
    new.geom := ST_SetSRID(ST_MakePoint(new.longitude, new.latitude), 4326);
    RETURN new;
END;
$BODY$
LANGUAGE plpgsql;

这只能在 BEFORE 触发器中完成:

CREATE TRIGGER triggerinsert
  BEFORE INSERT
  ON rdpr
  FOR EACH ROW
  EXECUTE PROCEDURE function_update();