My idea is to generate a unique ID for my table Alphanumeric for My table in SQL server So I use Newid function to do that and then I truncate the result to 8 character. My question is with this code I am sure to have a unique ID? Or maybe not here is the code:
DECLARE @r varchar(8)
SELECT @r = coalesce(@r, '') + n
FROM (SELECT top 8 CHAR(number) n
FROM master..spt_values
WHERE type = 'P' AND
(number between ascii(0) and ascii(9)
OR number between ascii('A') and ascii('Z')
OR number between ascii('a') and ascii('z'))
ORDER BY newid()) a
DECLARE @id varchar(10)
SET @id=CONVERT(varchar(8), @r)
DECLARE @myid varchar(10)
SELECT @myid=SUBSTRING(@r,1,2)+'-'+SUBSTRING(@r,3,3)+'-'+SUBSTRING(@r,6,3)
PRINT 'Value of @myid is: '+ @myid
NEWID() produces a v4 GUID. In that GUID scheme, the first 8 bytes can be any hexadecimal digit 0-F and will be composed entirely of randomly-generated data. That’s not guaranteed to be unique; in fact no v4 GUID is guaranteed to be unique, it’s just that the random bits (112 of 128) can represent one of 5.19 decillion numbers, so the odds of any two of them matching in the same system is infinitesimal. With only the first 8 bytes, you’ll only have 2^32 combinations, which may still seem like a lot (1 in 4 billion) but by the birthday problem, after a scant 77,000 have been generated you have a 50-50 shot at generating a duplicate.