October 07, 2010

AutoGenerate Numeric ID’s in SQL Server with No Sequence




Sometime back, I had written a post to AutoGenerate an AlphaNumeric Sequence in SQL Server

Tumo Jobas wrote back today asking if it was possible to use a similar method to generate a 10 digit number but with no sequence. Here’s one way that SQL MVP Peter Larsson uses often using NEWID() and I think it’s pretty slick. This solution will work in SQL Server 2005/2008.

DECLARE @TT TABLE
(
ID int, CircuitName varchar(10),
NonSeqID AS ABS(CHECKSUM(NEWID())) % 9000000000 + 1000000000
)

INSERT @TT
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'

SELECT * FROM @TT

OUTPUT

image

As shown above, the NonSeqID gets generated automatically using the NEWID() system function.


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

 
  Feedback:

comments

1 Response to "AutoGenerate Numeric ID’s in SQL Server with No Sequence"
  1. starsky51 said...
    October 7, 2010 at 1:14 PM

    Are these sequence numbers intended to be unique? I know it's a long shot but, in a big enough table, this will produce duplicates.

 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions