Generating random strings with T-SQL

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

    it's very simply.use it and enjoy.

    CREATE VIEW [dbo].[vwGetNewId]
    AS
    SELECT        NEWID() AS Id
    
    Creat FUNCTION [dbo].[fnGenerateRandomString](@length INT = 8)
    RETURNS NVARCHAR(MAX)
    AS
    BEGIN
    
    DECLARE @result CHAR(2000);
    
    DECLARE @String VARCHAR(2000);
    
    SET @String = 'abcdefghijklmnopqrstuvwxyz' + --lower letters
    'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + --upper letters
    '1234567890'; --number characters
    
    SELECT @result =
    (
        SELECT TOP (@length)
               SUBSTRING(@String, 1 + number, 1) AS [text()]
        FROM master..spt_values
        WHERE number < DATALENGTH(@String)
              AND type = 'P'
        ORDER BY
    (
        SELECT TOP 1 Id FROM dbo.vwGetNewId
    )   --instead of using newid()
        FOR XML PATH('')
    );
    
    RETURN @result;
    
    END;
    
    0 讨论(0)
  • 2020-11-29 18:55

    This will produce a string 96 characters in length, from the Base64 range (uppers, lowers, numbers, + and /). Adding 3 "NEWID()" will increase the length by 32, with no Base64 padding (=).

        SELECT 
            CAST(
                CONVERT(NVARCHAR(MAX),
                    CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                    +CONVERT(VARBINARY(8), NEWID())
                ,2) 
            AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
    

    If you are applying this to a set, make sure to introduce something from that set so that the NEWID() is recomputed, otherwise you'll get the same value each time:

      SELECT 
        U.UserName
        , LEFT(PseudoRandom.StringValue, LEN(U.Pwd)) AS FauxPwd
      FROM Users U
        CROSS APPLY (
            SELECT 
                CAST(
                    CONVERT(NVARCHAR(MAX),
                        CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), NEWID())
                        +CONVERT(VARBINARY(8), U.UserID)  -- Causes a recomute of all NEWID() calls
                    ,2) 
                AS XML).value('xs:base64Binary(xs:hexBinary(.))', 'VARCHAR(MAX)') AS StringValue
        ) PseudoRandom
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-29 18:55

    Heres something based on New Id.

    with list as 
    (
        select 1 as id,newid() as val
             union all
        select id + 1,NEWID()
        from    list   
        where   id + 1 < 10
    ) 
    select ID,val from list
    option (maxrecursion 0)
    
    0 讨论(0)
  • 2020-11-29 18:56

    Sometimes we need a lot of random things: love, kindness, vacation, etc. I have collected a few random generators over the years, and these are from Pinal Dave and a stackoverflow answer I found once. Refs below.

    --Adapted from Pinal Dave; http://blog.sqlauthority.com/2007/04/29/sql-server-random-number-generator-script-sql-query/
    SELECT 
        ABS( CAST( NEWID() AS BINARY( 6)) %1000) + 1 AS RandomInt
        , CAST( (ABS( CAST( NEWID() AS BINARY( 6)) %1000) + 1)/7.0123 AS NUMERIC( 15,4)) AS RandomNumeric
        , DATEADD( DAY, -1*(ABS( CAST( NEWID() AS BINARY( 6)) %1000) + 1), GETDATE()) AS RandomDate
        --This line from http://stackoverflow.com/questions/15038311/sql-password-generator-8-characters-upper-and-lower-and-include-a-number
        , CAST((ABS(CHECKSUM(NEWID()))%10) AS VARCHAR(1)) + CHAR(ASCII('a')+(ABS(CHECKSUM(NEWID()))%25)) + CHAR(ASCII('A')+(ABS(CHECKSUM(NEWID()))%25)) + LEFT(NEWID(),5) AS RandomChar
        , ABS(CHECKSUM(NEWID()))%50000+1 AS RandomID
    
    0 讨论(0)
  • 2020-11-29 18:58

    Here is a random alpha numeric generator

    print left(replace(newid(),'-',''),@length) //--@length is the length of random Num.
    
    0 讨论(0)
提交回复
热议问题