Microsoft Certified IT Professional Rudi Bruchez EI Microsoft Certified IT Professional

Rudi Bruchez EI · www.pachadata.com · rudi@pachadata.com · +33 6 22 48 76 99
Consulting, audit, performance tuning, solutions, training
SQL Server OLTP and BI / NoSQL

Version of October 14, 2026 (33a626f0) · https://www.pachadata.com/en/docs/howtos/data-modeling/autoincrement-by-parent/

Managing several auto-increments

Managing several auto-increments on a single table, when one column has to be numbered within the scope of another.

How do you manage several auto-increments on a single table, when one column has to be numbered within the scope of another?

The classic example is a table holding a document number — an invoice number, say — numbered per branch office:

CREATE TABLE dbo.Invoice (
    BranchNumber TINYINT NOT NULL,
    InvoiceNumber INT NOT NULL,
    CONSTRAINT pk_invoice PRIMARY KEY (InvoiceNumber, BranchNumber)
);

Here is a procedure that does it:

CREATE PROCEDURE [dbo].[AddInvoice]
    @BranchNumber tinyint
AS BEGIN
    SET NOCOUNT ON

    DECLARE @new_id int;

    SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

    BEGIN TRY

        BEGIN TRANSACTION;

        SELECT @new_id = ISNULL(max(InvoiceNumber),0) + 1
        FROM Invoice
        WHERE BranchNumber = @BranchNumber ;

        INSERT INTO Invoice (BranchNumber, InvoiceNumber)
        VALUES (@BranchNumber, @new_id) ;

        COMMIT TRAN

        SELECT @new_id AS id

    END TRY
    BEGIN CATCH
        ROLLBACK TRAN;

        SELECT NULL AS id;

        ;THROW;

    END CATCH

    SET TRANSACTION ISOLATION LEVEL READ COMMITTED;

    RETURN @new_id
END
GO

The SERIALIZABLE isolation level is what makes this correct: it takes a range lock on the rows for the branch being numbered, so two concurrent sessions cannot read the same maximum and allocate the same number.

Contact

I have been an independent SQL Server consultant since 2006. I help when an application slows down, when a server costs too much in storage or licenses, or when a migration must not stop production: audit and diagnosis, query and index tuning, migrations, high availability, training. On site, or as a remote audit delivered in five working days.

rudi@pachadata.com · +33 6 22 48 76 99 · www.pachadata.com/en/contact/