SQL 服务器中的短 guid / 从字符串转换为 uniqueidentifier

Short guid in SQL Server / converting from a character string to uniqueidentifier

我需要创建一个包含短 GUID 的列 。所以我发现了这样的事情:

alter table [dbo].[Table]
add InC UNIQUEIDENTIFIER not null default LEFT(NEWID(),6)

但是我得到错误:

Conversion failed when converting from a character string to uniqueidentifier.

我一直在努力

LEFT(CONVERT(varchar(36),NEWID()),6)

CONVERT(UNIQUEIDENTIFIER,LEFT(CONVERT(varchar(36),NEWID()),6))

但我仍然遇到同样的错误。

没有"short guid"这样的东西。 Guid,或 uniqueidentifier 是一个 16 字节的数据类型。你可以阅读它 in MSDN。这意味着长度必须 始终 为 16 个字节,并且您不能像您尝试的那样使用 6 个字符。

在同一篇 MSDN 文章中,您可以找到有关如何初始化此类型的说明:

A column or local variable of uniqueidentifier data type can be initialized to a value in the following ways:

  • By using the NEWID function.
  • By converting from a string constant in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a
    hexadecimal digit in the range 0-9 or a-f. For example,
    6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier
    value.

在您的情况下,您试图仅将 6 个字符转换为 uniqueidentifier,这显然失败了。

如果只想使用 6 个字符,只需使用 varchar(6):

alter table [dbo].[Table]
add InC varchar(6) not null default LEFT(NEWID(),6)

请记住,在这种情况下,不能保证此 guid 是唯一的。

我刚做了这个,因为我在互联网上找不到好的答案。

请记住,这是 128 位值的 64 位表示,因此它的冲突可能性是真实 GUID 的两倍。不处理 0.

函数采用 NEWID 值:6A10A273-4561-40D8-8D36-4D3B37E4A19C

并将其缩短为:7341xIlZseT

DECLARE @myid uniqueidentifier= NEWID()
select @myid
DECLARE @bigintdata BIGINT = cast(cast(reverse(NEWID()) as varbinary(max)) as bigint)
DECLARE @charSet VARCHAR(70) = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
DECLARE @cBase int = LEN(@charSet)
DECLARE @sUID varchar(22) = ''
DECLARE @x int

WHILE (@bigintdata <> 0)
BEGIN 
    SET @x = CAST(@bigintdata % @cBase as INT) + 1
    SET @bigintdata = @bigintdata / @cBase
    SET @sUID = SUBSTRING(@charSet, @x, 1) + @sUID;
END

SELECT @sUID

使用 CRYPT_GEN_RANDOM 而不是 NEWID 可以改善字符串的随机分布。

SELECT LEFT(CAST(CAST(CRYPT_GEN_RANDOM(16) AS UNIQUEIDENTIFIER) AS VARCHAR(50)), 6)