pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: André José Guergolet <AGuergolet@compugraf.com.br>
To: pgsql-sql@postgresql.org
Subject: Insert Data and autonumeric field
Date: Thu, 1 Feb 2007 16:09:22 -0300
Message-ID: <E426DDFE0FB5634AA3C997254DCBDE4EDF3C91@cgexc04.compugraf.com.br> (raw)

Hi everybody,
	I need to insert a row in a table and get the Id of this row ( My primary key ).

	Example:

		INSERT INTO table1 (date, field2, field3) VALUES (now,'value2','value3');
		SELECT last_value FROM seq_table1;

	I'm running each command apart. My application retrieves the last_value and uses it in another command:

		INSERT INTO table2 (pk1, field1, field2, field3) VALUES ( last_value_variable, 'value1','value2','value3');


PROBLEM: Many clients are getting duplicated IDs.

What is the best way of doing this?

I tried a function:

CREATE OR REPLACE FUNCTION fu_insertrow(int4, text)
  RETURNS int4 AS
$BODY$
DECLARE
    i_lastvalue INTEGER;
BEGIN

		INSERT INTO table1 (date, field1, field2) values (now(),$1,'$2');
		SELECT  i_lastvalue INTO i_lastvalue from "seq_ChamadaId";
		RETURN i_lastvalue;

END;
$BODY$
  LANGUAGE 'plpgsql' VOLATILE;



Using this function:

SELECT fu_insertrow(value2, value3);

The app gets the return value of the function above and uses it in my insert:
		INSERT INTO table2 (pk1, field1, field2, field3) VALUES ( function_return_variable, 'value1','value2','value3');

Suggestions?

Thanks,
	André Guergolet



view thread (3+ messages)

Message-ID: <E426DDFE0FB5634AA3C997254DCBDE4EDF3C91@cgexc04.compugraf.com.br>
Permalink:  ../E426DDFE0FB5634AA3C997254DCBDE4EDF3C91@cgexc04.compugraf.com.br/
Also on:    postgresql.org/message-id/E426DDFE0FB5634AA3C997254DCBDE4EDF3C91@cgexc04.compugraf.com.br

 · 

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 from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: AGuergolet@compugraf.com.br
  Subject: Re: Insert Data and autonumeric field
  In-Reply-To: <E426DDFE0FB5634AA3C997254DCBDE4EDF3C91@cgexc04.compugraf.com.br>
  References: <E426DDFE0FB5634AA3C997254DCBDE4EDF3C91@cgexc04.compugraf.com.br>

* 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