4

I want to write trigger to update table when new row is insert. I am using updatea Query like

UPDATE table SET
  geom = ST_SetSRID(ST_MakePoint(longitude, latitude), 4326) 
0

2 Answers 2

8

You need to use a BEFORE trigger and then assign the new value:

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;

This can only be done in a BEFORE trigger:

CREATE TRIGGER triggerinsert
  BEFORE INSERT
  ON rdpr
  FOR EACH ROW
  EXECUTE PROCEDURE function_update();
Sign up to request clarification or add additional context in comments.

Comments

0

I Solved by writing trigger function like

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;

and i wrote trigger to update

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

9 Comments

This is the wrong way to do it. Use a before trigger and don't use update
It is much more efficient to do that in an BEFORE trigger and assign a value instead of running a (costly) update statement for each and every row that is inserted. There is no need to do that in an AFTER trigger
Before insert not working for me.and i want to know why we should not use use 'update' in function
Why is before "not working"? Did you try the example in my answer? And you shouldn't use update because it is a lot slower then simply changing the row that is inserted.
Thanks for help.I have to update other geom column when insert into rdpr lat,long
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.