Generating random strings with T-SQL

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

    In SQL Server 2012+ we could concatenate the binaries of some (G)UIDs and then do a base64 conversion on the result.

    SELECT 
        textLen.textLen
    ,   left((
            select  CAST(newid() as varbinary(max)) + CAST(newid() as varbinary(max)) 
            where   textLen.textLen is not null /*force evaluation for each outer query row*/ 
            FOR XML PATH(''), BINARY BASE64
        ),textLen.textLen)   as  randomText
    FROM ( values (2),(4),(48) ) as textLen(textLen)    --define lengths here
    ;
    

    If you need longer strings (or you see = characters in the result) you need to add more + CAST(newid() as varbinary(max)) in the sub select.

提交回复
热议问题