Generating random strings with T-SQL

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

    I did this in SQL 2000 by creating a table that had characters I wanted to use, creating a view that selects characters from that table ordering by newid(), and then selecting the top 1 character from that view.

    CREATE VIEW dbo.vwCodeCharRandom
    AS
    SELECT TOP 100 PERCENT 
        CodeChar
    FROM dbo.tblCharacter
    ORDER BY 
        NEWID()
    
    ...
    
    SELECT TOP 1 CodeChar FROM dbo.vwCodeCharRandom
    

    Then you can simply pull characters from the view and concatenate them as needed.

    EDIT: Inspired by Stephan's response...

    select top 1 RandomChar from tblRandomCharacters order by newid()
    

    No need for a view (in fact I'm not sure why I did that - the code's from several years back). You can still specify the characters you want to use in the table.

提交回复
热议问题