Using crypt_gen_random to generate unique Serial Numbers

眉间皱痕 提交于 2020-01-06 05:30:07

问题


Trying to generate unique serial numbers with alphanumerics (A-Z,a-z,0-9) and no special characters.Used below code where sLength was min 10 and max 12 as defined in front end.

declare @sLength tinyint
declare @randomString varchar(50)
declare @counter tinyint
declare @nextChar char(1)
declare @rnd as float

set @sLength = 3
set @counter = 1
set @randomString = ''

while @counter <= @sLength
begin
    -- crypt_gen_random produces a random number. We need a random    
    -- float.
    select @rnd = cast(cast(cast(crypt_gen_random(2) AS int) AS float) /    
         65535  as float)  
    select @nextChar = char(48 + convert(int, (122-48+1) * @rnd))
    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
 select @randomString

Now the requirement has changed where we will be sending set of characters(min 6) & numbers(min 2) selected in front end. So i will be sending the parameter as follows @Include = 'ABCDEFG12345' and @Exclude='HIJKLMNOPQRSTUVXYZ06789'. Can someone suggest how do i change the below code as per the requirement.

My idea is to change the if ascii(@nextChar) not in line and add all the Ascii codes of the @Exclude characters & numbers, but not able to write the code for the same.


回答1:


I have modified the code to insert unique serial numbers as below.

declare @i int = 4000
while @i>0  
begin
declare @sLength tinyint
declare @randomString varchar(50)
declare @counter tinyint
declare @nextChar char(1)
declare @rnd as float
declare @ExcludeNumbers varchar(50)
DECLARE @XML XML
set @ExcludeNumbers='A,B,C,D,E,F,G,H,1,2,3'
SET @XML = CAST('<i>' + REPLACE(@ExcludeNumbers, ',', '</i><i>') + '</i>' AS XML)

set @sLength = 10
set @counter = 1
set @randomString = ''

while @counter <= @sLength
begin
    -- crypt_gen_random produces a random number. We need a random
        -- float.
    select @rnd = cast(cast(cast(crypt_gen_random(2) AS int) AS float) /    
         65535  as float)  
    select @nextChar = char(48 + convert(int, (122-48+1) * @rnd))
    if ascii(@nextChar)   in (select ASCII((x.i.value('.', 'VARCHAR(MAX)'))) FROM  @XML.nodes('i') x(i))
    begin
        select @randomString = @randomString + @nextChar
        set @counter = @counter + 1
    end
 end
 insert into serialNo values( @randomString);   
 select @i = @i-1 
 End


来源:https://stackoverflow.com/questions/58854667/using-crypt-gen-random-to-generate-unique-serial-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!