Sql server 在T-SQL中生成随机id(固定长度)

Sql server 在T-SQL中生成随机id(固定长度),sql-server,tsql,Sql Server,Tsql,可能重复: 我需要在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 = rand

可能重复:

我需要在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();
    }
公共静态字符串生成器域(int-size)
{
StringBuilder过程=新建StringBuilder();
随机=新随机();
对于(int i=0;i
用法示例:字符串输出=GeneratorDomain(15)

输出应该如下所示:O1REGVIDK7T4R9R

有人有一个想法…

创建过程生成器域
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)
@大小整数 作为 开始 声明@chars char(26)='abcdefghijklmnopqrstuvxyz' 声明@i int=0 声明@id varchar(max)=” 而@i<@size 开始 如果rand()>.5 设置@id=@id+子字符串(@chars,cast(天花板(rand()*26)为int),1) 其他的 将@id=@id+cast(floor(rand()*10)设置为varchar(2)) 设置@i=@i+1 结束 选择@id 结束 去 执行生成器域15 ------------------- BWZBKR601I8Z9KV (1行受影响)
创建过程生成器域
@大小整数
作为
开始
声明@chars char(26)='abcdefghijklmnopqrstuvxyz'
声明@i int=0
声明@id varchar(max)=”
而@i<@size
开始
如果rand()>.5
设置@id=@id+子字符串(@chars,cast(天花板(rand()*26)为int),1)
其他的
将@id=@id+cast(floor(rand()*10)设置为varchar(2))
设置@i=@i+1
结束
选择@id
结束
去
执行生成器域15
-------------------
BWZBKR601I8Z9KV
(1行受影响)

选择字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+它工作得很好,但我需要在ID中混合使用aplha和数字字符。那么,为什么你接受之前问题的字母数字答案?我假设名字中有“ID”,你想确保没有重复的字符?选择字符(rand()*26+65)+字符(rand()*26+65)+字符(rand()*26+65)+字符(rand()*26+65)+字符(rand()*26+65)+字符(rand()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)+字符(兰德()*26+65)它工作得很好,但我需要在ID中混合使用aplha和数字字符。那么,为什么您接受对您之前问题的字母数字答案?我假设名称中有“ID”,您希望确保没有重复的?