I need to use an existing table like this to facilitate rolling counters: –
CREATE TABLE [dbo].[IdentityCounter](
[CounterName] [nvarchar](255) NOT NULL,
[StartId] [bigint] NOT NULL,
[EndId] [bigint] NOT NULL,
[CurrentId] [bigint] NOT NULL,
[CreatedTime] [datetime] NULL,
[ModifiedTime] [datetime] NULL,
[Description] [nvarchar](255) NULL
) ON [PRIMARY]
For example say I have the following: –
CounterName "ReceiptNumber"
StartId 1
EndId 99999
etc. etc.
For a particular CounterName I want to be able to call a stored procedure or function to: –
-
To get me the next value and save that back to CurrentId and send the CurrentId back as the result
-
If the next value equals EndId + 1 then I need to make the next value equal to StartId and save that back to CurrentId. Also send the CurrentId back as the result.
-
There will be multiple applications calling this so need to ensure things remain consistent.
The counter is not a key it’s just something that needs to be passed to a 3rd party service.
What’s the best approach?
Thanks! ITG
First, I declare data that looks like the data in your question. It would be better if you declared this in your question so that we are all working with the same data. The data has one difference: the EndID is 5 instead of 99999 for demonstration purposes.
This procedure does what you ask for:
It returns a ‘scalar’ result set (one column, one row), which represents the value of
CurrentIDfor the given CounterName before the counter is incremented.Example of repeated execution:
Should output ten result sets similar to this sequence:
1,2,3,4,5,1,2,3,4,5.