Re: Simple plpgsql question

From: Terry Lee Tucker <terry(at)esc1(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: Simple plpgsql question
Date: 2006-04-14 09:03:10
Message-ID: 200604140503.10335.terry@esc1.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Thursday 13 April 2006 11:38 pm, "Todd Kennedy" <todd(dot)kennedy(at)gmail(dot)com>
thus communicated:
--> Hi,
-->
--> I have, what I hope to be, a simple question about plpgsql.
-->
--> I have a trigger on a table right now that updates a count everytime
--> that a new record is entered into a database (or removed).
-->
--> What I'd also like to do is have it create a new row in a different
--> table using the automatically assigned id as a reference, but I'm
--> unsure of how to obtain the id of the newly created row in the first
--> table.
-->
--> Example:
--> CREATE TABLE system_info (
--> id serial PRIMARY KEY,
--> name varchar(255),
--> value varchar(255)
--> );
--> INSERT INTO system_info (name,value) VALUES ('total_users','0');
-->
--> CREATE TABLE master (
--> id serial PRIMARY KEY,
--> name varchar(32) NOT NULL CHECK ( name <> ''),
--> UNIQUE(name)
--> );
-->
--> CREATE TABLE slave (
--> id serial PRIMARY KEY,
--> master_id integer REFERENCES master (id),
--> additional_info text
--> );
-->
--> CREATE OR REPLACE FUNCTION update_users() RETURNS trigger AS $$
--> BEGIN
--> IF TG_OP = 'DELETE' THEN
--> UPDATE system_info SET value=(value::integer)-1 WHERE name =
--> 'total_users'
--> RETURN OLD;
--> ELSEIF TG_OP = 'INSERT' THEN
--> UPDATE system_info SET value=(value::integer)+1 WHERE name =
--> 'total_users';
--> INSERT INTO slave (master_id) VALUES (THIS IS WHAT I NEED TO KNOW);
--> RETURN NEW;
--> END IF;
--> RETURN NULL;
--> END;
--> $$ LANGUAGE plpgsql;
-->
--> CREATE TRIGGER update_users AFTER INSERT OR DELETE ON master
--> FOR EACH ROW EXECUTE PROCEDURE update_users();
-->
-->
--> The part I need to know is the INSERT INTO statement in the procedure.
-->
--> Any help would be great.
-->
--> Thanks!
-->
--> ---------------------------(end of broadcast)---------------------------
--> TIP 4: Have you searched our list archives?
-->
--> http://archives.postgresql.org
-->

INSERT INTO slave (master_id) VALUES (new.id);

The buffer NEW contains all the "new" data.

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Volkan YAZICI 2006-04-14 09:13:44 Re: Simple plpgsql question
Previous Message Andreas Kretschmer 2006-04-14 07:52:40 Re: on select rule