SQL Server Code Example

Getting the Next Number in a Custom Number Format

A practical SQL Server and Azure SQL code example for Getting the Next Number in a Custom Number Format.

Example and Notes

Use this SQL Server example as a starting point for development, troubleshooting, reporting, or maintenance work. Review it against your schema, data volume, permissions, and SQL Server version before using it in production.

This sql script is very useful for getting the next number in a numeric order. Sometimes you'll have a requirement to have an incrementing number that has a special format. For example, your invoice number may be 2018-0001 (4 Digit year, dash, incrementing number starting at 1). There are a few ways this can be done, but if you want or need to do it one field, getting the number to increment can be a challenge. This sample script will show you how to accomplish this.

Create View viewNextNumber
AS

Select Max(Convert(Int,Right(YourNumberField,4))) AS NextID,
	Convert(Int,Left(YourNumberField,4)) AS InvoiceYear
From tblARInvoices
Where ISNUMERIC(Right(YourNumberField,4)) = 1
	And Convert(Int,Left(YourNumberField,4)) > 1900
Group By Convert(Int,Left(YourNumberField,4))
GO

Create Procedure uspGetNextID
	@prmYear Int --Pass in the Year you want to get the next ID For
AS
	
Declare @prmNextID Int
Select @prmNextID = NextID
From viewNextNumber
Where InvoiceYear = @prmYear

Select Convert(varchar(4),@prmYear) + Right('0000' + Convert(Varchar(4),IsNull(@prmNextID,0) + 1),4) AS NextID
GO

A sample call to this procedure would be:
Exec uspGetNextID 2018
which would return: 20180001


Production Review

WSI can adapt this script for your database, improve error handling, tune performance, document the logic, and help deploy it safely.

Readable Example

The original sample is preserved and presented in a cleaner professional layout.

Practical Context

Each example is framed around how it may be used in real SQL Server work.

Expert Support

WSI can adapt examples for your specific schema, business rules, and performance needs.

About Us

WSI is a small business and a leading provider of custom SQL Server/Azure programming and database solutions for government entities, Fortune 1000 companies, and emerging businesses. We are your custom SQL Server/Azure development experts.

Privacy Notice

We use essential cookies to make this site work. With your permission, we may also use analytics or marketing cookies.