Link to home
Start Free TrialLog in
Avatar of 32handicap
32handicap

asked on

How do i insert a sql record and get its key with competing multi threads

Hi,
I have a bunch of sync issues.  But here is the beginning of them and i hope its a simple one.  I have multi-threaded  program trying to insert sql records to a table with an autogenerated key.  When i insert the record, I would like to know the key of that record for later updates.  i noticed there is a merge statement, but it wasn't clear to me if it gurantees a "lock" with its statements.  I am not sure of the syntax, but if i use a merge statement to insert a record, and, (i think), get identiy, could two threads call the same merge statement at the same time and the first in line inserts the record, and before it executes the identity statement, the other inserts its record, and now the first gets the second record's identity since it was inserted before its, (the first thread's), identity statement was performed. ...Or, what is the best way to do what i am trying to do.  Not sure this makes any difference, but i am using SQL Compact Edition.
Thanks,
32Handicap

Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

with sql ce, you need to use
SELECT @@IDENTITY in a second query using the same connection.

and yes, ce edition does make a difference, as visibly the SCOPE_IDENTITY is not supported...
Avatar of 32handicap
32handicap

ASKER

Thanks for your quick reply angellll.  I believe both threads could be connected at the same time.  Could the first thread create a record, and before it could do the second querry, the second thread also creates a record.  and then when the first does the "SELECT @@IDENTITY in a second query " it actually gets the second threads record.  Or maybe that is the point of the @@IDENTITY in that it matches up with the connection.
 Thanks
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
yes, thanks.  it worked!