As others have mentioned, DBI has the
last_insert_id() method since 1.38. However, I discovered as I was trying to implement this for DBD::Sybase that it is broken up to and including the current 1.42 release. The bug is that a flag in the DBI dispatcher is incorrect so that DBI never calls the underlying DBD's implementation of
last_insert_id().
In addition,
last_insert_id() will only work if the underlying DBD has implemented it.
As you have discovered getting this value from the various database server engines requires some very different approaches. The most generic approach is to simply do a SELECT max(idvalue) FROM table right after the insert. If you are running with AutoCommit OFF, and if the server supports transactions then this should return the correct value, as long as you COMMIT after the SELECT max(). Otherwise this is open to a race condition in the case of multiple inserts to that same table.
And FYI - for Sybase and MS-SQL the last inserted id (IDENTITY value) can be retrieved with a SELECT @@identity.
Michael
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.