How to make unique random alphanumeric sequence in SQL Server

前端 未结 4 351
情话喂你
情话喂你 2021-01-16 20:21

I want to make unique random alphanumeric sequence to be the primary key for a database table.

Each char in the sequence is either a letter (a-z) or number (0-9)

4条回答
  •  滥情空心
    2021-01-16 21:14

    The drawback of NEWID() for this request is it limits the character pool to 0-9 and A-F. To define your own character pool, you have to role a custom solution.

    This solution adapted from Generating random strings with T-SQL

    --Define list of characters to use in random string
    DECLARE @CharPool VARCHAR(255)
    SET @CharPool = '0123456789abcdefghijkmnopqrstuvwxyz'
    
    --Store length of CharPool for use later
    DECLARE @PoolLength TINYINT
    SET @PoolLength = LEN(@CharPool) --36
    
    --Define random string length
    DECLARE @StringLength TINYINT
    SET @StringLength = 9
    
    --Declare target parameter for random string
    DECLARE @RandomString VARCHAR(255)
    SET @RandomString = ''
    
    --Loop control variable
    DECLARE @LoopCount TINYINT
    SET @LoopCount = 0
    
    --For each char in string, choose random char from char pool
    WHILE(@LoopCount < @StringLength)
    BEGIN
        SELECT @RandomString += SUBSTRING(@Charpool, CONVERT(int, RAND() * @PoolLength), 1)
        SELECT @LoopCount += 1
    END
    
    SELECT @RandomString
    

    http://sqlfiddle.com/#!6/9eecb/4354

    I must reiterate, however, that I agree with the others: this is a horrible idea.

提交回复
热议问题