The proper way to do this without using database dependent extensions like auto_increment, identity columns, etc. is to create a sequence table and access it within a transaction.

In pseudo code it would look something like this:

begin transaction update sequence_table set next_key = next_key + 1 where sequence_name = 'somename' select next_key from sequence_table where sequence_name = 'somename' commit transaction
The update acquires an exclusive lock on the row which will be held for the duration of the transaction. You then query the table to get the current value of next_key for this sequence. Once that value has been retrieved you commit the transaction, thus releasing the lock on the row.

This should (assuming the database engine handles transactions properly) guarantee that each client requesting a sequence value gets a unique value.

With Sybase (or MS-SQL) the whole sequence can be run as a single prepare()/execute() block. For other systems you probably simply want to set AutoCommit to false, do the update and then the query, followed by a $dbh->commit().

Note that this technique will create a hot-spot in your database server if you have a lot of request for new key values.

BTW - you can read a paper on the various key generation techniques for Sybase and/or MS-SQL servers at http://my.sybase.com/detail?id=860

Michael


In reply to Re: portable mysql auto_increment by mpeppler
in thread portable mysql auto_increment by schweini

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.