Generating random strings with T-SQL

前端 未结 27 1915
青春惊慌失措
青春惊慌失措 2020-11-29 18:10

If you wanted to generate a pseudorandom alphanumeric string using T-SQL, how would you do it? How would you exclude characters like dollar signs, dashes, and slashes from

27条回答
  •  野性不改
    2020-11-29 18:44

    Similar to the first example, but with more flexibility:

    -- min_length = 8, max_length = 12
    SET @Length = RAND() * 5 + 8
    -- SET @Length = RAND() * (max_length - min_length + 1) + min_length
    
    -- define allowable character explicitly - easy to read this way an easy to 
    -- omit easily confused chars like l (ell) and 1 (one) or 0 (zero) and O (oh)
    SET @CharPool = 
        'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789.,-_!$@#%^&*'
    SET @PoolLength = Len(@CharPool)
    
    SET @LoopCount = 0
    SET @RandomString = ''
    
    WHILE (@LoopCount < @Length) BEGIN
        SELECT @RandomString = @RandomString + 
            SUBSTRING(@Charpool, CONVERT(int, RAND() * @PoolLength), 1)
        SELECT @LoopCount = @LoopCount + 1
    END
    

    I forgot to mention one of the other features that makes this more flexible. By repeating blocks of characters in @CharPool, you can increase the weighting on certain characters so that they are more likely to be chosen.

提交回复
热议问题