Generating random strings with T-SQL

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

    If you are running SQL Server 2008 or greater, you could use the new cryptographic function crypt_gen_random() and then use base64 encoding to make it a string. This will work for up to 8000 characters.

    declare @BinaryData varbinary(max)
        , @CharacterData varchar(max)
        , @Length int = 2048
    
    set @BinaryData=crypt_gen_random (@Length) 
    
    set @CharacterData=cast('' as xml).value('xs:base64Binary(sql:variable("@BinaryData"))', 'varchar(max)')
    
    print @CharacterData
    

提交回复
热议问题