Generate Unique Number in SQL Server

Hi all!

I have a table with people data in it (names, addresses, etc), and I have a need to generate a unique 24 character identifier. It can be all numbers or contain letters from A to F (non-case sensitive).


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

this will do it without the - signs

select Left(NewID(),8)+Right(NewId(),12)+Left(NewId(),4)
As an addition: here is a shorter version that returns no dashes:

select left(replace(newid(), '-', ''),24)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

if Numeric is preferable you can do it like this

Select cast(ABS(CHECKSUM(NEWID())) % 99999999 as varchar) +cast(ABS(CHECKSUM(NEWID())) % 99999999 as varchar)+cast(ABS(CHECKSUM(NEWID())) % 99999999 as varchar)

but it will have to be stored as string, int or bigint will not hold 24 digits
you can use "NEWID()" to  generate unique keys of 36 character. If you use part of it via left() or right () or middle() function it cannot be guarantee that the value would be unique, although the chances of that happening are very rare.
pittcchsAuthor Commented:
Thanks, everyone! I ended up just using:


The 36-character ID will work for what I'm doing.

Anthony PerkinsCommented:
While that will work there is an implicit conversion from uniqueidentifier to character data, I would therefore suggest you instead use something like this:
REPLACE(CAST(NEWID() as varchar(36)),'-','')
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.