2012-12-19 99 views
1

可能重複:
Generating random string in T-SQL在T-SQL生成隨機ID(固定長度)

我需要轉換在T-SQL此C#方法:

public static string GenerateRandomID(int size) 
    { 
     StringBuilder pass = new StringBuilder(); 
     Random random = new Random(); 
     for (int i = 0; i < size; i++) 
     { 
      int binary = random.Next(0, 2); 
      switch (binary) 
      { 
       case 0: 
        char ch = (Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)))); 
        pass.Append(ch); 
        break; 
       case 1: 
        int num = random.Next(1, 10); 
        pass.Append(num); 
        break; 
      } 
     } 
     return pass.ToString(); 
    } 

使用示例:string output = GenerateRandomID(15)

輸出應該是這樣的:O1REGVIDK7T4R9R

有人有一個想法......

+0

選擇CHAR(RAND()* 26 + 65)+ CHAR(RAND()* 26 + 65)+ CHAR( rand()* 26 + 65) + char(rand()* 26 + 65)+ char(rand()* 26 + 65)+ char(rand()* 26 + 65) + char (rand()* 26 + 65)+ char(rand()* 26 + 65)+ char(rand()* 26 + 65) + char char(rand()* 26 + 65)+ char(rand()* 26 + 65)+ char(rand()* 26 + 65) – Maxime

+0

需要在ID中混合使用aplha和數字字符 – Maxime

+0

那麼,爲什麼你之前接受了對你的回答q uestion是字母數字? – Paparazzi

回答

1
create proc GenerateRandomID 
    @size  int 
as 
begin 

    declare @chars char(26) = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
    declare @i int = 0 
    declare @id varchar(max) = '' 

    while @i < @size 
    begin 
     if rand() > .5 
      set @id = @id + substring(@chars, cast(ceiling(rand() * 26) as int), 1) 
     else 
      set @id = @id + cast(floor(rand() * 10) as varchar(2)) 
     set @i = @i + 1 
    end 

    select @id 

end 
go 



exec GenerateRandomID 15 

------------------- 
BWZBKR601I8Z9KV 

(1 row(s) affected)