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.

1 comment:

  1. 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.

    ReplyDelete