Re: Simple plpgsql question - Mailing list pgsql-sql

From Volkan YAZICI
Subject Re: Simple plpgsql question
Date
Msg-id 20060414091344.GA209@alamut
Whole thread Raw
In response to Simple plpgsql question  ("Todd Kennedy" <todd.kennedy@gmail.com>)
Responses Programatically Backup Database Using Visual Basic
List pgsql-sql
On Apr 13 11:38, Todd Kennedy wrote:
> 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.

If I understand you right, you're refering to a SERIAL column with id.
If so, you can use currval() function over related SEQUENCE. Because of
INSERT/DELETE and trigger will be executed in the same session, they'll
be able to see current value of related sequence. Below is an example
about this:

BEGIN;

CREATE SEQUENCE trig_t_seq START 1;
CREATE TABLE trig_t (   id      bigint NOT NULL DEFAULT nextval('trig_t_seq'),   inf     int
);

CREATE FUNCTION trig_t_row_count() RETURNS trigger AS $$
BEGIN   IF TG_OP = 'INSERT' THEN       RAISE NOTICE 'Current SEQUENCE value: %', currval('trig_t_seq');   END IF;
RETURNNEW;
 
END
$$ LANGUAGE plpgsql;

CREATE TRIGGER trig_t_row_count_trig   AFTER INSERT   ON trig_t   FOR EACH ROW   EXECUTE PROCEDURE trig_t_row_count();

INSERT INTO trig_t (inf) VALUES (10);
INSERT INTO trig_t (inf) VALUES (20);
INSERT INTO trig_t (inf) VALUES (30);

ROLLBACK;


Regards.


pgsql-sql by date:

Previous
From: Terry Lee Tucker
Date:
Subject: Re: Simple plpgsql question
Next
From: ivan marchesini
Date:
Subject: Re: how to solve this problem