Generating random strings with T-SQL

前端 未结 27 1932
青春惊慌失措
青春惊慌失措 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:48

    For SQL Server 2016 and later, here is a really simple and relatively efficient expression to generate cryptographically random strings of a given byte length:

    --Generates 36 bytes (48 characters) of base64 encoded random data
    select r from OpenJson((select Crypt_Gen_Random(36) r for json path)) 
      with (r varchar(max))
    

    Note that the byte length is not the same as the encoded size; use the following from this article to convert:

    Bytes = 3 * (LengthInCharacters / 4) - Padding
    

提交回复
热议问题