in reply to Re: DBI and primary keys
in thread DBI and primary keys

Or, futhermore:     my ($last_id) = $db->selectrow_array("SELECT LAST_INSERT_ID()");

Replies are listed 'Best First'.
Re: Re: Re: DBI and primary keys
by $code or die (Deacon) on Mar 28, 2001 at 00:20 UTC
    But what if this is multiprocess where there might be two or three inserts that go in at (or close to) the same time? I might end up with the same "last row" for each of them?

    $ perldoc perldoc
      It's not efficient, and it depends on your dataset, but what's to prevent you from doing a select for the primary key of the row that matches your data exactly?

      If there's duplication of your values, you might have to order by the key, descending, and limit the results to one row... but you already have the exact values you've just inserted.

        Well, think of doing this on a muti-million row table.
        Without an index on all columns, of course.

        You'll wait hours, perhaps even days!

      I can only tell for Sybase ASE and mssql, select @@identity will give the identity-value for the last insert of your current session.
      the @@identity variable is per user session. To be frank, I've never done anything DBI work in the environment you're describing. That being said, you can check @@spid for each of your processes before you embark on this dangerous path. Unique spids should indicate @@identity is really unique for each process. Duplicate spids, should they appear, would indicate that your concern is correct.
      And in any case, whatever you do with the advice is your own gig :) feel free to ignore.
        It worked like this:
        INSERT INTO ......... SELECT @@IDENTITY as 'Identity';
        All in one statement, so after running execute, I did a call to fetch and got the identity. Nice!

        I really should go to bed - too much of a Perl(Monk) addict.

        $ perldoc perldoc