gpt4 book ai didi

sql - 同时使用 guid 和 int 作为表的唯一标识符有多常见?

转载 作者:行者123 更新时间:2023-12-03 09:00:15 25 4
gpt4 key购买 nike

我认为从 dba 的角度来看,Guid 通常是首选的唯一表行标识符。但我正在开发一个项目,其中开发人员和经理似乎想要一种通过 int 值引用事物的方法。我可以理解他们的观点,因为他们想要一种简单易用的方法来引用不同的实体。

我正在考虑为我的表使用一种模式,其中每个表都有一个代表 PK 列的 int Id 列,但它还会包含一个 Guid 列作为全局唯一标识符。使用这种类型的模式有多常见?

最佳答案

我不会说从 DBA 的角度来看 GUID 通常是首选。它更大(16 个字节,而不是 int 的 4 个字节或 bigint 的 8 个字节),并且随机变化引入了碎片,并由于页面预期生命周期较低而导致大表的 IO 增加。对于旋转媒体和有限的 RAM,这尤其是一个问题。

当实际需要 GUID 时,可以使用 GUID 值的顺序版本来避免其中一些问题,而不是引入另一个代理键。该值可以由 SQL Server 在列上使用 NEWSEQUENTIALID() 默认约束来分配,也可以在应用程序代码中生成,并为 SQL Server 正确排序字节。下面是后一种技术的 Windows C# 示例。

using System;
using System.Runtime.InteropServices;

public class Example
{
[DllImport("rpcrt4.dll", CharSet = CharSet.Auto)]
public static extern int UuidCreateSequential(ref Guid guid);

/// sequential guid for SQL Server
public static Guid NewSequentialGuid()
{
const int S_OK = 0;
const int RPC_S_UUID_LOCAL_ONLY = 1824;

Guid oldGuid = Guid.Empty;

int result = UuidCreateSequential(ref oldGuid);
if (result != S_OK && result != RPC_S_UUID_LOCAL_ONLY)
{
throw new ExternalException("UuidCreateSequential call failed", result);
}

byte[] oldGuidBytes = oldGuid.ToByteArray();
byte[] newGuidBytes = new byte[16];
oldGuidBytes.CopyTo(newGuidBytes, 0);

// swap low timestamp bytes (0-3)
newGuidBytes[0] = oldGuidBytes[3];
newGuidBytes[1] = oldGuidBytes[2];
newGuidBytes[2] = oldGuidBytes[1];
newGuidBytes[3] = oldGuidBytes[0];

// swap middle timestamp bytes (4-5)
newGuidBytes[4] = oldGuidBytes[5];
newGuidBytes[5] = oldGuidBytes[4];

// swap high timestamp bytes (6-7)
newGuidBytes[6] = oldGuidBytes[7];
newGuidBytes[7] = oldGuidBytes[6];

//remaining 8 bytes are unchanged (8-15)

return new Guid(newGuidBytes);

}

}

关于sql - 同时使用 guid 和 int 作为表的唯一标识符有多常见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51214655/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com