pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Volkan YAZICI <yazicivo@ttnet.net.tr>
To: Todd Kennedy <todd.kennedy@gmail.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: Simple plpgsql question
Date: Fri, 14 Apr 2006 12:13:44 +0300
Message-ID: <20060414091344.GA209@alamut> (raw)
In-Reply-To: <226d83de0604132038k66d58e75vc6d290efcba9f2f3@mail.gmail.com>
References: <226d83de0604132038k66d58e75vc6d290efcba9f2f3@mail.gmail.com>

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;
    
    RETURN NEW;
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.



view thread (3+ messages)

Message-ID: <20060414091344.GA209@alamut>
Permalink:  ../20060414091344.GA209@alamut/
Also on:    postgresql.org/message-id/20060414091344.GA209@alamut

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: yazicivo@ttnet.net.tr, todd.kennedy@gmail.com
  Subject: Re: Simple plpgsql question
  In-Reply-To: <20060414091344.GA209@alamut>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox