Currently working on a multi-tenant application, have an issue in generating identifier in a stored procedure.
I have a this table which has a meta information about tenant.
Tenant
TenantId
Name
IDPrefix, -->Like SFT
IDStart --> 000001
Client
TenantID
ClientIdentfier --> Like SFT000001
In a stored procedure I want to generate the next ClientIdentifier like SFT000002.
How can I do it based on last ClientIdentifier value + 1 ?
I know only taking last value with this below code.
select max(ClientID) + 1 from Client will give 1,2,etc
But I think I can’t do like
DECLARE @CIdentier Varchar(50);
select @CIdentier = select max(ClientIdentifier) + 1 from Client
to produce 'SFT000002
How can I do like this in a stored procedure?
Edit:
Tried mark_s answer and it worked like a charm!!!
This approach will be safe under load, e.g. it’s not going to return any duplicates, even if lots of client requests come in at the same time (this is “borrowed” from an answer by @remusrusanu to another question on SO).
Basically, you need a sequence table with columns
TenantID,TenantPrefixandCurrentValueand then you can use a stored procedure like this to safely fetch new values:The main point here is: you have to do the incrementing the
IDValueand the returning of it inside a singleUPDATEstatement. Only with this approach can you be safe under load – all the approaches that have aSELECTfirst, increment, and thenUPDATEare not safe and can return duplicates.Update: you cannot just include this snippet of code into a larger procedure of yours! Leave this procedure as is and just call it from your stored procedure – something like: