如何生成随机 Base36 ID

2021-09-10 00:00:00 sql tsql sql-server uniqueidentifier

有没有办法生成随机base36 标识符SQL Server 中定义的字符数?

Is there a way of generating random base36 identifiers with a defined character count in SQL Server?

我搜索并发现了许多将 base 36 转换为 int 以及将其转换为 int 的示例,但不是用于随机生成唯一 ID 的示例.

I have searched and found many examples of converting base 36 to int and vice versa, but not for randomly generating unique IDs.

推荐答案

这个解决方案有点冗长但有效并且可以轻松适应各种需求.以下是一些示例输出:

This solution a bit verbose but works and can easily be adapted to a variety of requirements. Here's some sample output:

aapx0k  k4fdbb  vzbl5x
8vr1bs  gbix1q  g5kctv
he6e50  m9j0m0  2vz53l
yw72hs  hgbo5h  3oen9v
6t4q75  337670  5sf3h4
yqr35s  xoh4hh  tc0wtf
w7trkj  lnnpdk  zk2ln1
1gt7qr  l6m72n  ja5kvm
kg6f9y  6t3b7a  ujfr0i
2jatgo  0yv8rv  wvbjfa

请注意,您需要创建一个视图来包装 UDF 中不允许使用的 RAND.所以这个解决方案需要两个 db 对象,一个视图和一个 udf.

Note that you need to create a view to wrap the use of RAND which is not allowed inside a UDF. So this solution needs two db objects, a view and a udf.

CREATE VIEW ViewRandInt AS (SELECT RAND() * 36 as RandInt)
GO

CREATE FUNCTION GetRandomBase36Id
(
    @charCount AS INT
) 
RETURNS VARCHAR(50) AS BEGIN

    DECLARE @characters CHAR(36),
            @result VARCHAR(MAX),
            @counter INT,
            @randNum INT

    SELECT @characters = '0123456789abcdefghijklmnopqrstuvwxyz',
           @result = '',
           @counter = 0;


    WHILE @counter < @charCount
    BEGIN
        SELECT @randNum = RandInt FROM ViewRandInt
        SET @result = @result + SUBSTRING(@characters, @randNum+1, 1)
        SET @counter = @counter + 1
    END

    RETURN @result;

END

-- Test:
SELECT dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)
, dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6), dbo.GetRandomBase36Id(6)

相关文章