tags:

views:

1128

answers:

5

I've got a simple stored procedure that does an insert to a table with an identity primary key column. I need to get the key that was generated by the insert. I would prefer to use the standard JDBC getGeneratedKeys method but I'm not sure what the stored procedure needs to do/return to build that result set. My end goal is to do this from Hibernate. I also tried using the select identity generator but it always returns 0.

A: 

On DB2/400 it seems to be the IDENTITY_VAL_LOCAL() function, that returns the most recently assigned value for an identity column.

http://publib.boulder.ibm.com/infocenter/db2luw/v8/topic/com.ibm.db2.udb.doc/admin/r0004231.htm

mjustin
True, but that doesn't work when the insert is in a stored procedure and you need to get the key after the procedure exits.
Brian Deterling
The key value could be placed in an out parameter for the stored procedure
mjustin
True again, but I was hoping there was a way to integrate cleanly into Hibernate which allows you to either use the JDBC getGeneratedKeys method or to define a query that will get the last key.
Brian Deterling
A: 

I've never tried the identity val local() function; in my own stored procedures, I just do a SELECT after the insert. But you can have a stored procedure return a result set:

create procedure proc1(
IN in_val
)
language sql
dynamic result sets 1

BEGIN
-- do insert

BEGIN
DECLARE c_out CURSOR WITH RETURN TO CLIENT FOR
  select max(key) as inserted_key from table where val = in_val
FOR READ ONLY;

OPEN c_out;
END;

END;

You can probably use identity val local replacing the select with "select identity val local() from sysibm.sysdummy1". I can't seem to get the underscores to work in markdown, but hopefully this is clear.

weiyin
That's my solution so far, but it requires using a custom Hibernate identity generator. I was hoping there was a way to make it work with the default Hibernate options (getGeneratedKeys or a second select using identity_val_local()).
Brian Deterling
What method are you using to call the stored procedure? See http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/tjvjdidn.htm
weiyin
This seems to be about as close as I can get. identity_val_local() doesn't maintain its value when the procedure exits.
Brian Deterling
A: 

The stored procedure can use identity val local to get the generated value and pass it as output parameter to Java program . Select after insert is not a good idea as other processes may have inserted new data to the table and would cause data integrity issues.

kishore
A: 

It is also possible to select from the insert:

SELECT pkey FROM FINAL TABLE (INSERT INTO tab(a, b, c, d) VALUES ... )
A: 

Fred Sobotka's answer worked for me.. thanks

som sankar basu