使用T-SQL生成随机字符串


95

如果要使用T-SQL生成伪随机的字母数字字符串,该怎么做?您如何从中排除美元符号,破折号和斜线之类的字符?

Answers:


40

当生成随机数据(特别是用于测试)时,使数据随机但可重现非常有用。秘诀是为随机函数使用显式种子,这样当再次使用相同种子运行测试时,它将再次产生完全相同的字符串。这是一个以可重现的方式生成对象名称的函数的简化示例:

alter procedure usp_generateIdentifier
    @minLen int = 1
    , @maxLen int = 256
    , @seed int output
    , @string varchar(8000) output
as
begin
    set nocount on;
    declare @length int;
    declare @alpha varchar(8000)
        , @digit varchar(8000)
        , @specials varchar(8000)
        , @first varchar(8000)
    declare @step bigint = rand(@seed) * 2147483647;

    select @alpha = 'qwertyuiopasdfghjklzxcvbnm'
        , @digit = '1234567890'
        , @specials = '_@# '
    select @first = @alpha + '_@';

    set  @seed = (rand((@seed+@step)%2147483647)*2147483647);

    select @length = @minLen + rand(@seed) * (@maxLen-@minLen)
        , @seed = (rand((@seed+@step)%2147483647)*2147483647);

    declare @dice int;
    select @dice = rand(@seed) * len(@first),
        @seed = (rand((@seed+@step)%2147483647)*2147483647);
    select @string = substring(@first, @dice, 1);

    while 0 < @length 
    begin
        select @dice = rand(@seed) * 100
            , @seed = (rand((@seed+@step)%2147483647)*2147483647);
        if (@dice < 10) -- 10% special chars
        begin
            select @dice = rand(@seed) * len(@specials)+1
                , @seed = (rand((@seed+@step)%2147483647)*2147483647);
            select @string = @string + substring(@specials, @dice, 1);
        end
        else if (@dice < 10+10) -- 10% digits
        begin
            select @dice = rand(@seed) * len(@digit)+1
                , @seed = (rand((@seed+@step)%2147483647)*2147483647);
            select @string = @string + substring(@digit, @dice, 1);
        end
        else -- rest 80% alpha
        begin
            declare @preseed int = @seed;
            select @dice = rand(@seed) * len(@alpha)+1
                , @seed = (rand((@seed+@step)%2147483647)*2147483647);

            select @string = @string + substring(@alpha, @dice, 1);
        end

        select @length = @length - 1;   
    end
end
go

运行测试时,调用者会生成一个随机种子,它将与测试运行相关联(将其保存在结果表中),然后将其传递给种子,类似于以下内容:

declare @seed int;
declare @string varchar(256);

select @seed = 1234; -- saved start seed

exec usp_generateIdentifier 
    @seed = @seed output
    , @string = @string output;
print @string;  
exec usp_generateIdentifier 
    @seed = @seed output
    , @string = @string output;
print @string;  
exec usp_generateIdentifier 
    @seed = @seed output
    , @string = @string output;
print @string;  

2016年2月17日更新:请参阅下面的评论,原始过程在推进随机种子的方式方面存在问题。我更新了代码,并修复了上述问题。


请注意,在我的示例中,重新播种主要是为了阐明这一点。实际上,只要随后的调用顺序是确定性的,它足以为每个会话播种RNG。
Remus Rusanu

2
我知道这是旧线程,但是代码为种子192804和529126返回了相同的字符串
davey

1
@RemusRusanu我也有兴趣回应davey的评论
l --''''''---------''''''''''

种子按配方前进@seed = rand(@seed+1)*2147483647。对于值529126,下一个值是1230039262,然后下一个值是192804。此后顺序相同。输出的第一个字符应该有所不同,但这不是因为一个错误的错误:SUBSTRING(..., 0, ...)返回索引0的空字符串,对于529126,此字符串“隐藏”生成的第一个字符。解决方法是计算@dice = rand(@seed) * len(@specials)+1以使索引为1。
Remus Rusanu

这个问题是由以下事实引起的:随机序列一旦达到一个共同的值,它们的进展就一样。如果需要,可以通过+1rand(@seed+1)其本身设置为随机值并仅从初始种子确定来避免这种情况。这样,即使系列达到相同的值,它们也会立即发散。
Remus Rusanu

202

使用GUID

SELECT @randomString = CONVERT(varchar(255), NEWID())

很短 ...


7
+1,非常简单。与RIGHT / SUBSTRING组合以将其截断为所需的长度。
约翰内斯·鲁道夫

2
我喜欢-甜蜜而简单。尽管它不具有“可预测性”功能,但非常适合数据生成。
madhurtanwani 2011年

6
千万不能使用权/子串截断的UUID,因为这将是既不独特,也不随机由于生成的UUID的方式!
ooxi 2014年

1
这很好,但是如果您使用此方法,请确保阅读以下内容:blogs.msdn.com/b/oldnewthing/archive/2008/06/27/8659071.aspx-注意GUID是Microsoft的UUID的实现,无论其含义是什么。 ooxi提到过,您需要小心切碎UUID。
克拉伦斯·刘

7
NEWID()中的字母字符为十六进制,因此您仅获得AF,而不获取其余字母。从这个意义上讲,这是限制。
smoore4'4

51

与第一个示例类似,但具有更大的灵活性:

-- min_length = 8, max_length = 12
SET @Length = RAND() * 5 + 8
-- SET @Length = RAND() * (max_length - min_length + 1) + min_length

-- define allowable character explicitly - easy to read this way an easy to 
-- omit easily confused chars like l (ell) and 1 (one) or 0 (zero) and O (oh)
SET @CharPool = 
    'abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ23456789.,-_!$@#%^&*'
SET @PoolLength = Len(@CharPool)

SET @LoopCount = 0
SET @RandomString = ''

WHILE (@LoopCount < @Length) BEGIN
    SELECT @RandomString = @RandomString + 
        SUBSTRING(@Charpool, CONVERT(int, RAND() * @PoolLength), 1)
    SELECT @LoopCount = @LoopCount + 1
END

我忘了提及使此功能更加灵活的其他功能之一。通过在@CharPool中重复字符块,可以增加某些字符的权重,以便更有可能选择它们。


1
+1这是一个很好的例程,我将其用作存储过程的一部分。
Marcello Miorelli,2014年

2
不错的解决方案。不幸的是,它在udf中不起作用。由于某种原因,它会出现此错误:“在函数中无效使用了副作用运算符'rand'。
rdans 2015年

12
SUBSTRING()调用中的此函数存在错误。应该是CONVERT(int, RAND() * @PoolLength) + 1(请注意添加的+1)。在T-SQL中,SUBSTRING从索引1开始,因此,此函数有时会添加一个空字符串(当索引为0时),而从不添加最后一个字符@CharPool
Dana Cartwright 2015年

@Dana Cartwright您能帮我解决我的问题吗?如果我需要使用上述字符集的恒定长度的序列号(如10个字母数字或12个字母数字序列号)怎么办?我们如何更改存储过程。在前端,我将提供使用Charpool生成的序列号总数,例如100或200。序列号的最小长度为10,最大为14(也作为参数提供)
Prathap Gangireddy

@PrathapGangireddy请问一个问题,对一个人的评论不是提出问题的正确地方
Dana Cartwright

31

使用以下代码返回短字符串:

SELECT SUBSTRING(CONVERT(varchar(40), NEWID()),0,9)

2
仅返回十六进制字符:0-9和AF
jumxozizi

19

如果运行的是SQL Server 2008或更高版本,则可以使用新的加密函数crypt_gen_random(),然后使用base64编码将其设置为字符串。最多可使用8000个字符。

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

16

我不是T-SQL方面的专家,但是我已经使用过的最简单的方法是这样的:

select char((rand()*25 + 65))+char((rand()*25 + 65))

这将生成两个字符(AZ,ASCII 65-90)。


11
select left(NEWID(),5)

这将返回Guid字符串中最左边的5个字符

Example run
------------
11C89
9DB02

1
尽管此解决方案不适用于生产系统,因为经过数千次左右的迁移后,您很容易获得重复的副本,但对于在调试或测试某些东西时获得随机字符串的快速简便方法而言,它非常有用。
Ian1971

我用它来为500个登录生成一个随机的4个字母的密码,这非常适合。是的,对于大数据和其他目的,请使用更多字符。
Hammad Khan 2014年

1
对于安全密码,NEWID()不够随机,因此,根据您的要求,您需要特别小心。使用5个字符,您将在大约1500条记录后发生冲突。在我的测试中,使用4个字符,您会在55-800条记录之间发生冲突。
Ian1971

@ Ian1971作为临时密码,它仍然可以。可以说我给您的ATM卡有4个字母的大头针。也许也可以向另一个800位用户发出相同的密码,但是您极不可能将其卡与密码一起使用。这几乎是一个随机数,可以临时访问。
Hammad Khan 2014年


5

对于一个随机字母,可以使用:

select substring('ABCDEFGHIJKLMNOPQRSTUVWXYZ',
                 (abs(checksum(newid())) % 26)+1, 1)

使用newid()vs与之间的重要区别在于rand(),如果您返回多行,则将newid()针对每行分别计算,而rand()针对整个查询仅计算一次。


4

这对我有用:我只需要为ID生成三个随机的字母数字字符,但是它就可以在不超过15个左右的任何长度下工作。

declare @DesiredLength as int = 3;
select substring(replace(newID(),'-',''),cast(RAND()*(31-@DesiredLength) as int),@DesiredLength);

仅返回十六进制字符:0-9和AF
jumxozizi

是的,我想你是对的。它不是真正的“字母数字”,因为您没有得到>“ F”的字符。
布赖恩

3

有很多好的答案,但是到目前为止,它们都没有一个允许自定义的字符池并用作列的默认值。我希望能够做这样的事情:

alter table MY_TABLE add MY_COLUMN char(20) not null
  default dbo.GenerateToken(crypt_gen_random(20))

所以我想出了这个。如果修改,请当心硬编码的数字32。

-- Converts a varbinary of length N into a varchar of length N.
-- Recommend passing in the result of CRYPT_GEN_RANDOM(N).
create function GenerateToken(@randomBytes varbinary(max))
returns varchar(max) as begin

-- Limit to 32 chars to get an even distribution (because 32 divides 256) with easy math.
declare @allowedChars char(32);
set @allowedChars = 'abcdefghijklmnopqrstuvwxyz012345';

declare @oneByte tinyint;
declare @oneChar char(1);
declare @index int;
declare @token varchar(max);

set @index = 0;
set @token = '';

while @index < datalength(@randomBytes)
begin
    -- Get next byte, use it to index into @allowedChars, and append to @token.
    -- Note: substring is 1-based.
    set @index = @index + 1;
    select @oneByte = convert(tinyint, substring(@randomBytes, @index, 1));
    select @oneChar = substring(@allowedChars, 1 + (@oneByte % 32), 1); -- 32 is the number of @allowedChars
    select @token = @token + @oneChar;
end

return @token;

end

2

我意识到这是一个古老的问题,答案很多。但是,当我发现此问题时,我也在Saeid Hasani的TechNet上找到了最近的文章。

T-SQL:如何生成随机密码

虽然该解决方案着重于密码,但它适用于一般情况。Saeid会通过各种考虑来寻求解决方案。这很有启发性。

包含本文中所有代码块的脚本可以通过TechNet Gallery单独获得,但我肯定会从本文开始。


1

我使用我开发的这个过程,简单地规定了要显示在输入变量中的字符,也可以定义长度。希望这种格式很好,我是堆栈溢出的新手。

IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID(N'GenerateARandomString'))
DROP PROCEDURE GenerateARandomString
GO

CREATE PROCEDURE GenerateARandomString
(
     @DESIREDLENGTH         INTEGER = 100,                  
     @NUMBERS               VARCHAR(50) 
        = '0123456789',     
     @ALPHABET              VARCHAR(100) 
        ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
     @SPECIALS              VARCHAR(50) 
        = '_=+-$£%^&*()"!@~#:', 
     @RANDOMSTRING          VARCHAR(8000)   OUT 

)

AS

BEGIN
    -- Author David Riley
    -- Version 1.0 
    -- You could alter to one big string .e.e numebrs , alpha special etc
    -- added for more felxibility in case I want to extend i.e put logic  in for 3 numbers, 2 pecials 3 numbers etc
    -- for now just randomly pick one of them

    DECLARE @SWAP                   VARCHAR(8000);      -- Will be used as a tempoary buffer 
    DECLARE @SELECTOR               INTEGER = 0;

    DECLARE @CURRENTLENGHT          INTEGER = 0;
    WHILE @CURRENTLENGHT < @DESIREDLENGTH
    BEGIN

        -- Do we want a number, special character or Alphabet Randonly decide?
        SET @SELECTOR  = CAST(ABS(CHECKSUM(NEWID())) % 3 AS INTEGER);   -- Always three 1 number , 2 alphaBET , 3 special;
        IF @SELECTOR = 0
        BEGIN
            SET @SELECTOR = 3
        END;

        -- SET SWAP VARIABLE AS DESIRED
        SELECT @SWAP = CASE WHEN @SELECTOR = 1 THEN @NUMBERS WHEN @SELECTOR = 2 THEN @ALPHABET ELSE @SPECIALS END;

        -- MAKE THE SELECTION
        SET @SELECTOR  = CAST(ABS(CHECKSUM(NEWID())) % LEN(@SWAP) AS INTEGER);
        IF @SELECTOR = 0
        BEGIN
            SET @SELECTOR = LEN(@SWAP)
        END;

        SET @RANDOMSTRING = ISNULL(@RANDOMSTRING,'') + SUBSTRING(@SWAP,@SELECTOR,1);
        SET @CURRENTLENGHT = LEN(@RANDOMSTRING);
    END;

END;

GO

DECLARE @RANDOMSTRING VARCHAR(8000)

EXEC GenerateARandomString @RANDOMSTRING = @RANDOMSTRING OUT

SELECT @RANDOMSTRING

1

有时我们需要很多随机的东西:爱,友善,休假等。这些年来,我收集了一些随机生成器,这些生成器来自Pinal Dave和我一次发现的stackoverflow答案。参考如下。

--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

1
感谢您发布方便的随机生成器集合
iiminov

1

这是我今天想出的一个(因为我对现有答案不够满意)。

这个生成基于的随机字符串的临时表,基于newid(),但还支持自定义字符集(因此不只是0-9和AF),自定义长度(最大为255,限制为硬编码,但可以更改),以及自定义数量的随机记录。

这是源代码(希望注释帮助):

/**
 * First, we're going to define the random parameters for this
 * snippet. Changing these variables will alter the entire
 * outcome of this script. Try not to break everything.
 *
 * @var {int}       count    The number of random values to generate.
 * @var {int}       length   The length of each random value.
 * @var {char(62)}  charset  The characters that may appear within a random value.
 */

-- Define the parameters
declare @count int = 10
declare @length int = 60
declare @charset char(62) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'

/**
 * We're going to define our random table to be twice the maximum
 * length (255 * 2 = 510). It's twice because we will be using
 * the newid() method, which produces hex guids. More later.
 */

-- Create the random table
declare @random table (
    value nvarchar(510)
)

/**
 * We'll use two characters from newid() to make one character in
 * the random value. Each newid() provides us 32 hex characters,
 * so we'll have to make multiple calls depending on length.
 */

-- Determine how many "newid()" calls we'll need per random value
declare @iterations int = ceiling(@length * 2 / 32.0)

/**
 * Before we start making multiple calls to "newid", we need to
 * start with an initial value. Since we know that we need at
 * least one call, we will go ahead and satisfy the count.
 */

-- Iterate up to the count
declare @i int = 0 while @i < @count begin set @i = @i + 1

    -- Insert a new set of 32 hex characters for each record, limiting to @length * 2
    insert into @random
        select substring(replace(newid(), '-', ''), 1, @length * 2)

end

-- Now fill the remaining the remaining length using a series of update clauses
set @i = 0 while @i < @iterations begin set @i = @i + 1

    -- Append to the original value, limit @length * 2
    update @random
        set value = substring(value + replace(newid(), '-', ''), 1, @length * 2)

end

/**
 * Now that we have our base random values, we can convert them
 * into the final random values. We'll do this by taking two
 * hex characters, and mapping then to one charset value.
 */

-- Convert the base random values to charset random values
set @i = 0 while @i < @length begin set @i = @i + 1

    /**
     * Explaining what's actually going on here is a bit complex. I'll
     * do my best to break it down step by step. Hopefully you'll be
     * able to follow along. If not, then wise up and come back.
     */

    -- Perform the update
    update @random
        set value =

            /**
             * Everything we're doing here is in a loop. The @i variable marks
             * what character of the final result we're assigning. We will
             * start off by taking everything we've already done first.
             */

            -- Take the part of the string up to the current index
            substring(value, 1, @i - 1) +

            /**
             * Now we're going to convert the two hex values after the index,
             * and convert them to a single charset value. We can do this
             * with a bit of math and conversions, so function away!
             */

            -- Replace the current two hex values with one charset value
            substring(@charset, convert(int, convert(varbinary(1), substring(value, @i, 2), 2)) * (len(@charset) - 1) / 255 + 1, 1) +
    --  (1) -------------------------------------------------------^^^^^^^^^^^^^^^^^^^^^^^-----------------------------------------
    --  (2) ---------------------------------^^^^^^^^^^^^^^^^^^^^^^11111111111111111111111^^^^-------------------------------------
    --  (3) --------------------^^^^^^^^^^^^^2222222222222222222222222222222222222222222222222^------------------------------------
    --  (4) --------------------333333333333333333333333333333333333333333333333333333333333333---^^^^^^^^^^^^^^^^^^^^^^^^^--------
    --  (5) --------------------333333333333333333333333333333333333333333333333333333333333333^^^4444444444444444444444444--------
    --  (6) --------------------5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555^^^^----
    --  (7) ^^^^^^^^^^^^^^^^^^^^66666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666^^^^

            /**
             * (1) - Determine the two hex characters that we'll be converting (ex: 0F, AB, 3C, etc.)
             * (2) - Convert those two hex characters to a a proper hexadecimal (ex: 0x0F, 0xAB, 0x3C, etc.)
             * (3) - Convert the hexadecimals to integers (ex: 15, 171, 60)
             * (4) - Determine the conversion ratio between the length of @charset and the range of hexadecimals (255)
             * (5) - Multiply the integer from (3) with the conversion ratio from (4) to get a value between 0 and (len(@charset) - 1)
             * (6) - Add 1 to the offset from (5) to get a value between 1 and len(@charset), since strings start at 1 in SQL
             * (7) - Use the offset from (6) and grab a single character from @subset
             */

            /**
             * All that is left is to add in everything we have left to do.
             * We will eventually process the entire string, but we will
             * take things one step at a time. Round and round we go!
             */

            -- Append everything we have left to do
            substring(value, 2 + @i, len(value))

end

-- Select the results
select value
from @random

它不是一个存储过程,但是将它变成一个并不困难。这也不是太慢了(我花了0.3秒才能生成1,000个长度为60的结果,这比我个人需要的还要多),这是我所做的所有字符串突变的最初关注点之一。

这里的主要要点是,我没有尝试创建自己的随机数生成器,并且我的字符集不受限制。我只是在使用SQL拥有的随机生成器(我知道有rand(),但是对于表结果来说并不是很好)。希望这种方法在这里可以将两种答案结合起来:过于简单(即只是newid())和过于复杂(即自定义随机数算法)。

它也很简短(减去注释),并且易于理解(至少对我而言),这在我的书中总是加号。

但是,这种方法无法播种,因此每次都将是真正随机的,并且您将无法以任何可靠的方式复制同一组数据。OP没有将其列为要求,但我知道有些人正在寻找这种东西。

我知道我在这里参加聚会迟到了,但是希望有人会觉得这很有用。


0

我首先遇到了此博客文章,然后针对当前项目使用了以下存储过程(抱歉,格式很奇怪):

CREATE PROCEDURE [dbo].[SpGenerateRandomString]
@sLength tinyint = 10,
@randomString varchar(50) OUTPUT
AS
BEGIN
SET NOCOUNT ON
DECLARE @counter tinyint
DECLARE @nextChar char(1)
SET @counter = 1
SET @randomString = 

WHILE @counter <= @sLength
BEGIN
SELECT @nextChar = CHAR(48 + CONVERT(INT, (122-48+1)*RAND()))

IF ASCII(@nextChar) not in (58,59,60,61,62,63,64,91,92,93,94,95,96)
BEGIN
SELECT @randomString = @randomString + @nextChar
SET @counter = @counter + 1
END
END
END

0

我在SQL 2000中通过创建一个包含要使用的字符的表,创建一个从表中选择字符的视图(按newid()进行排序),然后从该视图中选择前1个字符的视图来做到这一点。

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

...

SELECT TOP 1 CodeChar FROM dbo.vwCodeCharRandom

然后,您可以简单地从视图中提取字符并根据需要将它们连接起来。

编辑:灵感来自斯蒂芬的回应...

select top 1 RandomChar from tblRandomCharacters order by newid()

不需要视图(实际上,我不确定为什么要这样做-代码是几年前的)。您仍然可以在表中指定要使用的字符。


0

这是基于新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-9和AF
jumxozizi

0

我想分享或回馈社区...它基于ASCII,解决方案虽然不完美,但效果很好。享受,戈兰B。

/* 
-- predictable masking of ascii chars within a given decimal range
-- purpose: 
--    i needed an alternative to hashing alg. or uniqueidentifier functions
--    because i wanted to be able to revert to original char set if possible ("if", the operative word)
-- notes: wrap below in a scalar function if desired (i.e. recommended)
-- by goran biljetina (2014-02-25)
*/

declare 
@length int
,@position int
,@maskedString varchar(500)
,@inpString varchar(500)
,@offsetAsciiUp1 smallint
,@offsetAsciiDown1 smallint
,@ipOffset smallint
,@asciiHiBound smallint
,@asciiLoBound smallint


set @ipOffset=null
set @offsetAsciiUp1=1
set @offsetAsciiDown1=-1
set @asciiHiBound=126 --> up to and NOT including
set @asciiLoBound=31 --> up from and NOT including

SET @inpString = '{"config":"some string value", "boolAttr": true}'
SET @length = LEN(@inpString)

SET @position = 1
SET @maskedString = ''

--> MASK:
---------
WHILE (@position < @length+1) BEGIN
    SELECT @maskedString = @maskedString + 
    ISNULL(
        CASE 
        WHEN ASCII(SUBSTRING(@inpString,@position,1))>@asciiLoBound AND ASCII(SUBSTRING(@inpString,@position,1))<@asciiHiBound
         THEN
            CHAR(ASCII(SUBSTRING(@inpString,@position,1))+
            (case when @ipOffset is null then
            case when ASCII(SUBSTRING(@inpString,@position,1))%2=0 then @offsetAsciiUp1 else @offsetAsciiDown1 end
            else @ipOffset end))
        WHEN ASCII(SUBSTRING(@inpString,@position,1))<=@asciiLoBound
         THEN '('+CONVERT(varchar,ASCII(SUBSTRING(@Inpstring,@position,1))+1000)+')' --> wrap for decode
        WHEN ASCII(SUBSTRING(@inpString,@position,1))>=@asciiHiBound
         THEN '('+CONVERT(varchar,ASCII(SUBSTRING(@inpString,@position,1))+1000)+')' --> wrap for decode
        END
        ,'')
    SELECT @position = @position + 1
END

select @MaskedString


SET @inpString = @maskedString
SET @length = LEN(@inpString)

SET @position = 1
SET @maskedString = ''

--> UNMASK (Limited to within ascii lo-hi bound):
-------------------------------------------------
WHILE (@position < @length+1) BEGIN
    SELECT @maskedString = @maskedString + 
    ISNULL(
        CASE 
        WHEN ASCII(SUBSTRING(@inpString,@position,1))>@asciiLoBound AND ASCII(SUBSTRING(@inpString,@position,1))<@asciiHiBound
         THEN
            CHAR(ASCII(SUBSTRING(@inpString,@position,1))+
            (case when @ipOffset is null then
            case when ASCII(SUBSTRING(@inpString,@position,1))%2=1 then @offsetAsciiDown1 else @offsetAsciiUp1 end
            else @ipOffset*(-1) end))
        ELSE ''
        END
        ,'')
    SELECT @position = @position + 1
END

select @maskedString

我确实意识到我的解决方案不是随机字符生成,而是可预测的字符串混淆... :)
Goran B.

0

这与其他答案之一一样,将rand与种子一起使用,但是不必在每次调用时都提供种子。在第一个电话上提供它就足够了。

这是我修改的代码。

IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND object_id = OBJECT_ID(N'usp_generateIdentifier'))
DROP PROCEDURE usp_generateIdentifier
GO

create procedure usp_generateIdentifier
    @minLen int = 1
    , @maxLen int = 256
    , @seed int output
    , @string varchar(8000) output
as
begin
    set nocount on;
    declare @length int;
    declare @alpha varchar(8000)
        , @digit varchar(8000)
        , @specials varchar(8000)
        , @first varchar(8000)

    select @alpha = 'qwertyuiopasdfghjklzxcvbnm'
        , @digit = '1234567890'
        , @specials = '_@#$&'
    select @first = @alpha + '_@';

    -- Establish our rand seed and store a new seed for next time
    set  @seed = (rand(@seed)*2147483647);

    select @length = @minLen + rand() * (@maxLen-@minLen);
    --print @length

    declare @dice int;
    select @dice = rand() * len(@first);
    select @string = substring(@first, @dice, 1);

    while 0 < @length 
    begin
        select @dice = rand() * 100;
        if (@dice < 10) -- 10% special chars
        begin
            select @dice = rand() * len(@specials)+1;
            select @string = @string + substring(@specials, @dice, 1);
        end
        else if (@dice < 10+10) -- 10% digits
        begin
            select @dice = rand() * len(@digit)+1;
            select @string = @string + substring(@digit, @dice, 1);
        end
        else -- rest 80% alpha
        begin
            select @dice = rand() * len(@alpha)+1;

            select @string = @string + substring(@alpha, @dice, 1);
        end

        select @length = @length - 1;   
    end
end
go

0

SQL Server 2012+中,我们可以串联某些(G)UID的二进制文件,然后对结果进行base64转换。

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
;

如果需要更长的字符串(或=在结果中看到字符),则需要+ CAST(newid() as varbinary(max))在子选择中添加更多的字符串。


0

因此,我喜欢上面的许多答案,但我一直在寻找自然界中有些随机的东西。我还希望有一种方法可以明确地调出排除的字符。以下是我的解决方案,使用的视图调用CRYPT_GEN_RANDOM来获取密码随机数。在我的示例中,我只选择了一个8字节的随机数。请注意,您可以增加此大小,也可以根据需要利用函数的种子参数。这是文档的链接:https : //docs.microsoft.com/zh-cn/sql/t-sql/functions/crypt-gen-random-transact-sql

CREATE VIEW [dbo].[VW_CRYPT_GEN_RANDOM_8]
AS
SELECT CRYPT_GEN_RANDOM(8) as [value];

创建视图的原因是因为CRYPT_GEN_RANDOM不能直接从函数中调用。

从那里,我创建了一个标量函数,该函数接受一个长度和一个字符串参数,该参数可以包含逗号分隔的排除字符字符串。

CREATE FUNCTION [dbo].[fn_GenerateRandomString]
( 
    @length INT,
    @excludedCharacters VARCHAR(200) --Comma delimited string of excluded characters
)
RETURNS VARCHAR(Max)
BEGIN
    DECLARE @returnValue VARCHAR(Max) = ''
        , @asciiValue INT
        , @currentCharacter CHAR;

    --Optional concept, you can add default excluded characters
    SET @excludedCharacters = CONCAT(@excludedCharacters,',^,*,(,),-,_,=,+,[,{,],},\,|,;,:,'',",<,.,>,/,`,~');

    --Table of excluded characters
    DECLARE @excludedCharactersTable table([asciiValue] INT);

    --Insert comma
    INSERT INTO @excludedCharactersTable SELECT 44;

    --Stores the ascii value of the excluded characters in the table
    INSERT INTO @excludedCharactersTable
    SELECT ASCII(TRIM(value))
    FROM STRING_SPLIT(@excludedCharacters, ',')
    WHERE LEN(TRIM(value)) = 1;

    --Keep looping until the return string is filled
    WHILE(LEN(@returnValue) < @length)
    BEGIN
        --Get a truly random integer values from 33-126
        SET @asciiValue = (SELECT TOP 1 (ABS(CONVERT(INT, [value])) % 94) + 33 FROM [dbo].[VW_CRYPT_GEN_RANDOM_8]);

        --If the random integer value is not in the excluded characters table then append to the return string
        IF(NOT EXISTS(SELECT * 
                        FROM @excludedCharactersTable 
                        WHERE [asciiValue] = @asciiValue))
        BEGIN
            SET @returnValue = @returnValue + CHAR(@asciiValue);
        END
    END

    RETURN(@returnValue);
END

下面是如何调用该函数的示例。

SELECT [dbo].[fn_GenerateRandomString](8,'!,@,#,$,%,&,?');

〜干杯


0

非常简单。使用它并享受。

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

这将产生一个长度为96个字符的字符串,其长度来自Base64范围(上,下,数字,+和/)。添加3个“ NEWID()”将使长度增加32,而没有Base64填充(=)。

    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

如果要将其应用于集合,请确保引入该集合中的某些内容,以便重新计算NEWID(),否则每次将获得相同的值:

  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

对于SQL Server 2016及更高版本,这是一个非常简单且相对有效的表达式,用于生成给定字节长度的加密随机字符串:

--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))

请注意,字节长度与编码后的大小不同。使用下面的这个文章转换:

Bytes = 3 * (LengthInCharacters / 4) - Padding

0

基于本文中各种有用的答复,我找到了一些我喜欢的选项的组合。

DECLARE @UserId BIGINT = 12345 -- a uniqueId in my system
SELECT LOWER(REPLACE(NEWID(),'-','')) + CONVERT(VARCHAR, @UserId)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.