0

I have a following question, for example I have a following table:

CREATE TABLE "regions" (gid serial PRIMARY KEY,
"__gid" int8,
"name" varchar(20),
"language" varchar(7),
"population" int8);

And I want to insert some records, say one of the values for "name" is - 'B', what sort of code would I have to write to change 'B' to 'English-Speaking'? Is that done with some sort of trigger? So would I have to write a trigger to change the values automatically on insert? Any help greatly appriciated!!!

2
  • So you want to insert into regions (name, ...) values ('B', ...) and have it put 'English-Speaking' into name instead? Why do you want to do such a thing? Commented May 10, 2013 at 4:07
  • I just required to write it for college... If it is 'C' for example it would be 'French-Speaking' Commented May 10, 2013 at 4:09

2 Answers 2

1

It's an UPDATE statement which will do what you wish, in this case:

UPDATE regions set name = 'English-Speaking' where name = 'B';

To put this in a function use something like:

CREATE OR REPLACE FUNCTION  insert_into_wgs()
RETURNS void AS
$$
BEGIN
UPDATE regions SET name = 'English-Speaking' WHERE name = 'B';
END
$$
LANGUAGE 'pgpsql';

Then you create a trigger to run this function:

CREATE TRIGGER log_update
    AFTER UPDATE ON accounts
    FOR EACH ROW
    WHEN (OLD.* IS DISTINCT FROM NEW.*)
    EXECUTE PROCEDURE
    insert_into_wgs();
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I want to do it automatically - without having to run UPDATE
See my edit for a revised answer, given your comment, @AndreiIvanov
There is few changes I had to make - but it worked! Thanks a lot!
0

Assuming I've guessed what you mean correctly from your description:

You will need a simple BEFORE INSERT OR UPDATE ... FOR EACH ROW EXECUTE trigger to invoke a PL/PgSQL trigger procedure that changes the value of the NEW record and then does a RETURN NEW.

The documentation contains abundant details, and since this is homework I'm not going to provide a complete example. Start with CREATE TRIGGER and PL/pgSQL trigger procedures.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.