如何生成随机 Base36 ID

时间:2022-11-04
本文介绍了如何生成随机 Base36 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有没有办法生成随机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)

这篇关于如何生成随机 Base36 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一条:使用SQL server将一个主表分成多个表 下一条:从sql server获取windows用户登录名

相关文章

最新文章