Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Here is a way to do it using a table to store your last sequence number. The stored proc is very simple, most of the stuff in there is because I'm lazy and don't like surprises should I forget something so...here it is:</p> <p>----- Create the sequence value table.</p> <pre><code>SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[SequenceTbl] ( [CurrentValue] [bigint] ) ON [PRIMARY] GO </code></pre> <hr> <p>-----------------Create the stored procedure</p> <pre><code>SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE procedure [dbo].[sp_NextInSequence](@SkipCount BigInt = 1) AS BEGIN BEGIN TRANSACTION DECLARE @NextInSequence BigInt; IF NOT EXISTS ( SELECT CurrentValue FROM SequenceTbl ) INSERT INTO SequenceTbl (CurrentValue) VALUES (0); SELECT TOP 1 @NextInSequence = ISNULL(CurrentValue, 0) + 1 FROM SequenceTbl WITH (HoldLock); UPDATE SequenceTbl WITH (UPDLOCK) SET CurrentValue = @NextInSequence + (@SkipCount - 1); COMMIT TRANSACTION RETURN @NextInSequence END; GO </code></pre> <hr> <p>--------Use the stored procedure in Sql Manager to retrive a test value.</p> <pre><code>declare @NextInSequence BigInt exec @NextInSequence = sp_NextInSequence; --exec @NextInSequence = sp_NextInSequence &lt;skipcount&gt;; select NextInSequence = @NextInSequence; </code></pre> <p>-----Show the current table value.</p> <pre><code>select * from SequenceTbl; </code></pre> <p>The astute will notice that there is a parameter (optional) for the stored proc. This is to allow the caller to reserve a block of ID's in the instance that the caller has more than one record that needs a unique id - using the SkipCount, the caller need make only a single call for however many IDs are needed. The entire "IF EXISTS...INSERT INTO..." block can be removed if you remember to insert a record when the table is created. If you also remember to insert that record with a value (your seed value - a number which will never be used as an ID), you can also remove the ISNULL(...) portion of the select and just use CurrentValue + 1. Now, before anyone makes a comment, please note that I am a software engineer, <em>not</em> a dba! So, any <em>constructive</em> criticism concerning the use of "Top 1", "With (HoldLock)" and "With (UPDLock)" is welcome. I don't know how well this will scale but this works OK for me so far...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload