Re: SQL INSERT/TRIGGER Help

From: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Re: SQL INSERT/TRIGGER Help
Date: 2007-12-10 07:43:47
Message-ID: 20071210074347.GB917@a-kretschmer.de
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

am Mon, dem 10.12.2007, um 9:27:58 +0200 mailte Poovendran Moodley folgendes:
> I'm not really sure how to the currval() method. I've read up on it and I
> noticed it works with nextval() and setval(). The parameter for currval() is a
> regex - is there a regex to represent the most recently automatically generated
> number ( i.e. a serial field)? If there isn't, I was thinking that a trigger
> could be used so that when an INSERT is executed against the Observation_Value

Okay, i explain this a little bit more:

first, i create two tables, master and slave. master contains a
serial-field, this field is referenced by the slave table:

test=# create table master (id serial primary key, name text);
NOTICE: CREATE TABLE will create implicit sequence "master_id_seq" for serial column "master.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "master_pkey" for table "master"
CREATE TABLE
test=*# create table slave(master_id int references master, val text);
CREATE TABLE

Now i have 2 tables and a sequence named 'master_id_seq', and now the
insert's:

test=*# insert into master (name) values ('test');
INSERT 0 1
test=*# insert into slave (master_id, val) values (currval('master_id_seq'), 'value');
INSERT 0 1

The parameter for currval() is the name of the sequence. Note: you have to
insert in the master table first, this calls the nextval() for the
sequence. After, within this database session, you can use currval() to
obtain the actual value for this sequence. And yes, this way is safe
also for concurrency.

Andreas
--
Andreas Kretschmer
Kontakt: Heynitz: 035242/47150, D1: 0160/7141639 (mehr: -> Header)
GnuPG-ID: 0x3FFF606C, privat 0x7F4584DA http://wwwkeys.de.pgp.net

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Poovendran Moodley 2007-12-10 09:13:49 Re: SQL INSERT/TRIGGER Help
Previous Message Poovendran Moodley 2007-12-10 07:27:58 Re: SQL INSERT/TRIGGER Help