Wednesday, September 2, 2009

Retrieving the id of last inserted record - PostgreSQL

PostgreSQL 8.3

To get the id of the inserted record we make use of the new function "returning" along with "nextval".

Syntax:
Dim NextRecord as integer

Dim cmd As Odbc.OdbcCommand = New OdbcCommand ("INSERT INTO mytable (myid, column1, column2) VALUES (nextval('mytable_myid_seq'), ?,?)
RETURNING myid;")


cmd.Parameters.Add(New OdbcParameter("@column1", column1value))
cmd.Parameters.Add(New OdbcParameter("@column2", column2value))

NextRecord = cmd.ExecuteScalar

Explanation:
myid is the auto increment column in the table.
nextval retrives the number which will be generated
returning returns the new myid.

Note: if your column names or sequence have capitals then do add double quotes
example: ""ColumnNames""


Enjoy~

Mehdi

No comments:

Post a Comment