在T-SQL中生成随机ID(固定长度)

时间:2012-12-19 19:08:28

标签: sql-server tsql

  

可能重复:
  Generating random string in T-SQL

我需要在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

有人有想法......

1 个答案:

答案 0 :(得分: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)