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.

---------------------------(end of broadcast)---------------------------
TIP 5: don't forget to increase your free space map settings

Reply via email to