Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-26 03:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found