Hello,
We have a mulit-user application using SQL Server 2008 and VB 2010. There is a process in place to get the next record ID of our Order table, but it needs to be modified to ensure that two users are not getting the same value at the same time, which could obviously cause a primary key violation if the users are using that ID when they create new orders. I believe I know what to do to fix this, but I would appreciate confirmation from the DB gurus we have on this forum.
We keep the "LastOrderID" as a field in a one-record table, let's call it AppParms, and we essentially read that record to get the ID, add 1 to it, and update the table with that new ID.
Here is pseudocode for what is currently in place:
----------------------------------------------------------------------
Sql = "SELECT LastOrderID FROM AppParms"
' use reader object to execute the Sql and get the value of LastOrderID
TheNewID = LastOrderID + 1
' "TheNewID" is then used in the app to later ultimately insert the new order into the Order table
Sql = "UPDATE AppParms SET LastOrderID = " & TheNewID
' execute the SQL
----------------------------------------------------------------------
Here is what I believe I need to do to modify the above:
----------------------------------------------------------------------
' execute a "BeginTransaction" on the DB connection
Sql = "SELECT LastOrderID FROM AppParms (UPDLOCK)"
' use reader object to execute the Sql and get the value of LastOrderID
TheNewID = LastOrderID + 1
' "TheNewID" is then used in the app to later ultimately insert the new order into the Order table
Sql = "UPDATE AppParms SET LastOrderID = " & TheNewID
' execute the SQL
' execute a "Commit" on the transaction object
----------------------------------------------------------------------
Do you concur? If not, what would I need to do instead?


Reply With Quote
