Itβs a bad idea to use MAX because with the right locking mechanism, you wonβt be able to insert rows into multiple threads for the same region. If everything is all right for you, you can only create one user at a time, and if your tests show that MAX scales even with a large number of users in each district, it may be convenient to use. In short, when dealing with identity as much as possible, you should rely on IDENTITY. Actually.
But if this is not possible, one solution is to process the identifiers in a separate table.
Create Table DistrictID ( DistrictCode char(2), LastID Int, Constraint PK_DistrictCode Primary Key Clustered (DistrictCode) );
Then you increment the LastID counter. It is important that the identifier increment is a transaction divided by a user creation transaction if you want to create many users in parallel threads. You can restrict the ability to generate only an identifier.
The code might look like this:
Create Procedure usp_GetNewId(@DistrictCode char(2), @NewId Int Output) As Set NoCount On; Set Transaction Isolation Level Repeatable Read; Begin Tran; Select @NewId = LastID From DistrictID With (XLock) Where DistrictCode = @DistrictCode; Update DistrictID Set LastID = LastID + 1 Where DistrictCode = @DistrictCode; Commit Tran;
Keywords Repeatable reading and XLOCK are the minimum you need to avoid two threads to get the same identifier. If the table does not have all counties, you need to change Repeatable reading to Serializable and develop Update using Insert .
source share