Home » SQL & PL/SQL » SQL & PL/SQL » Get back pk value that trigger created on insert
Get back pk value that trigger created on insert [message #9268] Wed, 29 October 2003 16:23 Go to next message
David Karr
Messages: 5
Registered: October 2003
Junior Member
I'm using Oracle 8.1.7.

I now have a table whose pk value is set by an insert trigger which uses a sequence. So, when I do an insert, I don't specify the pk value, but the trigger sets one.

Now, I need a clean strategy for knowing exactly what pk value resulted from the insert. How can this work? I'm using Java/JDK1.4/JDBC.

If I do a query on "<sequence>.currval" will that give me 1+ the value, even in the presence of multiple transactions?
Re: Get back pk value that trigger created on insert [message #9269 is a reply to message #9268] Wed, 29 October 2003 17:07 Go to previous messageGo to next message
Todd Barry
Messages: 4819
Registered: August 2001
Senior Member
The RETURNING clause is the best way to get the value back:

sql> create sequence t_seq;
 
Sequence created.
 
sql> create table t (pk int, name varchar2(30));
 
Table created.
 
sql> create or replace trigger t_trg
  2  before insert on t
  3  for each row
  4  begin
  5    select t_seq.nextval into :new.pk from dual;
  6  end;
  7  /
 
Trigger created.
 
sql> var pk_val number;
sql> set sqlp sql>
sql>insert into t (name) values ('Test') returning pk into :pk_val;
 
1 row created.
 
sql>print pk_val
 
   PK_VAL
---------
        1
 
sql>insert into t (name) values ('Second') returning pk into :pk_val;
 
1 row created.
 
sql>print pk_val
 
   PK_VAL
---------
        2
Re: Get back pk value that trigger created on insert [message #9270 is a reply to message #9269] Wed, 29 October 2003 20:57 Go to previous messageGo to next message
Vishal
Messages: 86
Registered: August 2000
Member
Hi Todd,

This method suggested by you gives the value in a bind variable. Is there any way to get this value if inserting through JDBC.

Thanks in advance,
Vishal
Re: Get back pk value that trigger created on insert [message #9284 is a reply to message #9270] Thu, 30 October 2003 10:27 Go to previous message
Todd Barry
Messages: 4819
Registered: August 2001
Senior Member
Same approach:

CallableStatement cs =
  conn.prepareCall("begin insert into t (name) values (?) returning pk_column into ?; end;");


And then use registerOutParameter for register that OUT parameter and getInt after the execute to read the value assigned by the sequence.
Previous Topic: Clarification
Next Topic: Trigger issue
Goto Forum:
  


Current Time: Thu Apr 25 20:37:55 CDT 2024