SQL Server 中的 GUID 是什么数据类型?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16521052/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What data type is GUID in SQL server?
提问by Ondrej Peterka
How is GUID internally stored and compared by SQL (particularly MS SQL server 2008)? Is it a number or string? Also, is there a big performance hit when using GUID as primary key?
SQL(尤其是 MS SQL Server 2008)如何在内部存储和比较 GUID?它是数字还是字符串?另外,当使用 GUID 作为主键时是否有很大的性能损失?
Besides the problem with clustering mentioned here: What are the best practices for using a GUID as a primary key, specifically regarding performance?
除了这里提到的集群问题: 使用 GUID 作为主键的最佳实践是什么,特别是关于性能?
I think it should be 128bit number (as described here), but I cannot find mode details on how is it implemented in SQL server.
我觉得应该是128位数字(如描述在这里),但我不能找到它是如何在SQL服务器中实现模式的详细信息。
采纳答案by Remus Rusanu
16 bytes, exactly as the GUID structure:
16 字节,与GUID 结构完全相同:
typedef struct _GUID {
DWORD Data1;
WORD Data2;
WORD Data3;
BYTE Data4[8];
} GUID;
回答by MikeLim
Performance wise, normal GUID
is slower than INT
in SQL Server
性能方面,正常GUID
情况下比INT
SQL Server慢
If you plan to use GUID
, use uniqueidentifier
instead of varchar
as data type. Microsoft did not mention how they implement it, there is some speed optimization when you use uniqueidentifier
as the data type.
如果您打算使用GUID
,请使用uniqueidentifier
而不是varchar
作为数据类型。微软没有提到他们如何实现它,当你uniqueidentifier
用作数据类型时有一些速度优化。
To use GUID
as primary key without sacrificing speed of integer, make the GUID
value sequential. Define uniqueidentifier
data type as PK, set the default to NEWSEQUENTIALID()
.
要GUID
在不牺牲整数速度的情况下用作主键,请使GUID
值保持顺序。定义uniqueidentifier
数据类型为PK,默认为NEWSEQUENTIALID()
.
See NEWSEQUENTIALID (Transact-SQL)for further details.
有关更多详细信息,请参阅NEWSEQUENTIALID (Transact-SQL)。
As to how sequential GUID
values help performance, see The Cost of GUIDs as Primary Keys.
关于顺序GUID
值如何帮助性能,请参阅GUID 作为主键的成本。
回答by Alireza Zamani
You can also use nvarchar(128).
您也可以使用 nvarchar(128)。
The next-best option would be a binary(16) column:
次佳选项是 binary(16) 列:
standard GUIDs are exactly 16 bytes in length. If you must store it as a string, the length really comes down to how you choose to encode it. As hex (AKA base-16 encoding) without hyphens it would be 32 characters (two hex digits per byte).
标准 GUID 的长度正好是 16 个字节。如果您必须将其存储为字符串,则长度实际上取决于您选择如何对其进行编码。作为没有连字符的十六进制(AKA base-16 编码),它将是 32 个字符(每字节两个十六进制数字)。