1

可能重复:
在 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();
    }

使用示例:字符串输出 = GenerateRandomID(15)

输出应如下所示:O1REGVIDK7T4R9R

有人有想法...

4

1 回答 1

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)
于 2012-12-19T19:44:47.183 回答