generate seemingly random unique numeric ID in SQL Server

后端 未结 5 1822
被撕碎了的回忆
被撕碎了的回忆 2020-12-06 15:19

I need to use SQL Server to generate seemingly random unique 8-digit numeric ID (can pad zeros at front). Is there a built-in functionality for this? I saw

5条回答
  •  长情又很酷
    2020-12-06 15:26

    you can use NEWID() to generate uniqueIdentifier data which always random and unique each time

    To get 8 character you can use substring, left etc function.

    select substring( cast( NEWID() as varchar(100)),0,8)
    

    or new logic for uniqueness:- http://forums.asp.net/t/1474299.aspx?How+to+generate+unique+key+of+fixed+length+20+digit+in+sql+server+2005+

    select Left(NewID(),4)+Right(NewId(),4)
    

    you can use random() function for this too.

    check this links: How do I generate random number for each row in a TSQL Select?

    How to get numeric random uniqueid in SQL Server

    Updated If you want to unique value int data-type and 8 character long. Good to make a identity column like below, which is good for 8 character length data means (10,000,000). But after that it gives you exception. So be carefull which logic you want.(Still I say, its bad idea). store as random value as above with more length so uniqueness comes.

    create table temp (id numeric(8,0) IDENTITY(1,1) NOT NULL, value1 varchar ) --if you want do not stop after 8 character , give int datatype.
    
    insert into temp values( 'a'), ('b'), ('c')
    
    select * from temp
    
    drop table temp
    

    Finally

    It's not guaranteed unique but it's hard to get duplicates with NEWID()(refer above link forums.asp.net)

提交回复
热议问题