gb73 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Brothers,
I am relatively new to perl and this is my first post in this forum, so please forgive my question style, broken English and my inexperience with Perl. I have searched all day a solution for the problem below and I am now reaching the total desperation.
I am using DBI to insert a new record into a table on MSSQL server db. The table contains a Primary key auto generated using the NewID() function.
My question is how to retrieve the ID of the new record just created using DBI. I have tried using the code below:
my $sql = "mystoredprocedure 'value1','value2'";<br> my $sth = dbh->prepare($sql);<br> my $ret = $sth->execute();<br> my $recs = $sth->fetchrow_hashref();<br>

Obviously the code above ends where the fetchrow is.

I think that the 2 solutions below are feasible however I would like to see if there is a more ‘elegant’ and appropriate solution for the problem above.
1 – Execute a ‘select newid()’ , retrieve the ID and use that as a primary key for the new records (fast)
2 - Search the table using a select with the value that I have just inserted (slow)

Thank you in advance

Replies are listed 'Best First'.
Re: Retreiving GUID after insert
by Corion (Patriarch) on Jun 13, 2007 at 06:58 UTC
Re: Retreiving GUID after insert
by Anonymous Monk on Jun 13, 2007 at 02:38 UTC
      I think the OP refers to Microsoft SQL Server, not MySQL.
      --
      print map{chr}unpack(q{A3}x24,q{074117115116032097110111116104101114032080101114108032104097099107101114})
Re: Retreiving GUID after insert
by andreas1234567 (Vicar) on Jun 13, 2007 at 07:51 UTC
    I would add an output parameter to the mystoredprocedure and have the procedure return the id, all in a single operation.

    Read the bind_param_inout section of the DBI documentation.

    --
    print map{chr}unpack(q{A3}x24,q{074117115116032097110111116104101114032080101114108032104097099107101114})