I have a primary key OrderHeaderID that auto increments, but i also need to auto increment the OrderNumber based what company the order is placed for.
Current Strategy: (On my insert statement to the table)
(SELECT MAX(OrderNumber) + 1 FROM OrderHeader WHERE CompanyID = @CompanyID)
Issue: once i started testing with some volume, i started getting duplicate key errors:
Table OrderHeader:
OrderHeaderID CompanyID OrderNumber
1 1 10000
2 1 10001
3 1 10002
4 2 10000
5 2 10001
6 2 10002
To solve your concurrency issue, you’ll have to raise the isolation level of your
SELECTstatement, and then subsequently perform theINSERTinside of the same transaction.The specific syntax of this will vary for each RBDMS, but here’s an example using Sql Server:
This places an exclusive lock on the rows read during the
SELECTstatement, which will prevent another instance of this routine from running concurrently. Instead, the second instance will be blocked until the original process performs theINSERTandCOMMIT, at which point the second instance will then proceed to read and lock the newly generated value.