生成10位由大小寫字母和數字組成的隨機激活碼


/*
select char(65+ceiling(rand()*25))   --隨機字母(大寫)
select char(97+ceiling(rand()*25))   --隨機字母(小寫)
select cast(ceiling(rand()*9) as varchar(1))   --隨機數字 1至9的隨機數字(整數)
*/

DECLARE  @i    int           
DECLARE  @flag int
DECLARE  @SerialNumber  nvarchar(20)

--初始化設定
SET  @i=1
SET  @SerialNumber = ''

--生成10位隨機碼
WHILE @i<11
BEGIN
    --設置隨機,這個隨機會選擇字母(大小寫)還是數字
    SET @flag=ceiling(rand()*3) 

    IF @flag=1 
    BEGIN
       --隨機字母(大寫)
       select @SerialNumber=@SerialNumber+char(65+ceiling(rand()*25))
    END
    else if @flag=2
         begin
             --隨機字母(小寫)
             select @SerialNumber=@SerialNumber+char(97+ceiling(rand()*25))
         end
         else begin
             --隨機數字 1至9的隨機數字(整數)
             select @SerialNumber=@SerialNumber+cast(ceiling(rand()*9) as varchar

(1))
         end

     --進行下一個循環
     SET @i=@i+1
END

SELECT @SerialNumber as '生成的10位激活碼'

 

 

---但是有的時候需要前面幾位必須是純英文字母,后面幾位純數字或隨意字母和數字

/*
select char(65+ceiling(rand()*25))   --隨機字母(大寫)
select char(97+ceiling(rand()*25))   --隨機字母(小寫)
select cast(ceiling(rand()*9) as varchar(1))   --隨機數字 1至9的隨機數字(整數)
*/

DECLARE  @i    int           
DECLARE  @flag INT
DECLARE  @SerialNumber nvarchar(20)

--初始化設定
SET  @i=1
SET  @SerialNumber = ''

--生成10位隨機碼
WHILE @i<11
BEGIN
    --設置隨機,這個隨機會選擇字母(大小寫)還是數字
    SET @flag=ceiling(rand()*3) 

    IF @i < 6  --前五位是字母
    BEGIN
            IF @flag=1 
            BEGIN
                 --隨機字母(大寫)
                 select @SerialNumber=@SerialNumber+char(65+ceiling(rand()*25))
            END
            ELSE BEGIN
                 --隨機字母(小寫)
                 select @SerialNumber=@SerialNumber+char(97+ceiling(rand()*25))
            END

     END
     ELSE BEGIN  --后面幾位是字母或數字
            IF @flag=1 
            BEGIN
               --隨機字母(大寫)
               select @SerialNumber=@SerialNumber+char(65+ceiling(rand()*25))
            END
            else if @flag=2
                 begin
                     --隨機字母(小寫)
                     select @SerialNumber=@SerialNumber+char(97+ceiling(rand()*25))
                 end
                 else begin
                     --隨機數字 1至9的隨機數字(整數)
                     select @SerialNumber=@SerialNumber+cast(ceiling(rand()*9) as varchar(1))
                 end
     END
     
     
     --進行下一個循環
     SET @i=@i+1
END

SELECT @SerialNumber as '生成的10位激活碼'

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM