AutoGenerate an AlphaNumeric Sequence in SQL Server

I was recently solving a requirement of a client where the client needed a Unique Alphanumeric Sequence Number to be generated using the following business rules:

UniqueID = Code (TT) + Current Datetime + ID

Here's how I generated the UniqueID



ID  int, CircuitName varchar(10),

UniqueID  AS 'TT' + REPLACE(CONVERT(varchar, GETDATE(),101),'/','')

+ REPLACE(CONVERT(varchar, GETDATE(),108),':',''

+ CAST(ID as varchar(10))




SELECT 1, 'Circuit 1' UNION ALL

SELECT 2, 'Circuit 2' UNION ALL

SELECT 3, 'Circuit 3' UNION ALL

SELECT 4, 'Circuit 4' UNION ALL

SELECT 5, 'Circuit 5' UNION ALL

SELECT 6, 'Circuit 6' UNION ALL

SELECT 7, 'Circuit 7' UNION ALL

SELECT 8, 'Circuit 8' UNION ALL

SELECT 9, 'Circuit 9' UNION ALL

SELECT 10, 'Circuit 10'




ID    CircuitName    UniqueID

1    Circuit 1    TT051220091517481

2    Circuit 2    TT051220091517482

3    Circuit 3    TT051220091517483

4    Circuit 4    TT051220091517484

5    Circuit 5    TT051220091517485

6    Circuit 6    TT051220091517486

7    Circuit 7    TT051220091517487

8    Circuit 8    TT051220091517488

9    Circuit 9    TT051220091517489

10    Circuit 10    TT0512200915174810

About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook


Tumo Jobas said...

excellent topic. Can I use this method to generate an id of integers but not in any sequence, just random 10 digit numbers?

Suprotim Agarwal said...

Tumo yes there is a way that I use using the NEWID(). Just wait for a couple of hours and I will update this post with a solution.

Suprotim Agarwal said...

Here's the solution you are looking out for AutoGenerate Numeric ID’s in SQL Server with No Sequence