SQL Server中GUID的数据类型是什么?

时间:2021-06-12 16:32:07

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 Server中实现的模式详细信息。

2 个解决方案

#1


8  

16 bytes, exactly as the GUID structure:

16字节,与GUID结构完全相同:

typedef struct _GUID {
  DWORD Data1;
  WORD  Data2;
  WORD  Data3;
  BYTE  Data4[8];
} GUID;

#2


13  

Performance wise, normal GUID is slower than INT in SQL Server

性能方面,正常的GUID比SQL Server中的INT慢

If you plan to use GUID, use uniqueidentifer instead of varchar as data type. Microsoft did not mention how they implement it, there is some speed optimization when you use uniqueIdentifer as the data type.

如果您计划使用GUID,请使用uniqueidentifer而不是varchar作为数据类型。 Microsoft没有提到它们是如何实现的,当您使用uniqueIdentifer作为数据类型时,存在一些速度优化。

To use GUID as primary key without sacrificing speed of integer, make the GUID value sequential. Define uniqueidentifer data type as PK, set the default to NEWSEQUENTIALID().

要在不牺牲整数速度的情况下将GUID用作主键,请使GUID值顺序。将uniqueidentifer数据类型定义为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成本作为主键。

#1


8  

16 bytes, exactly as the GUID structure:

16字节,与GUID结构完全相同:

typedef struct _GUID {
  DWORD Data1;
  WORD  Data2;
  WORD  Data3;
  BYTE  Data4[8];
} GUID;

#2


13  

Performance wise, normal GUID is slower than INT in SQL Server

性能方面,正常的GUID比SQL Server中的INT慢

If you plan to use GUID, use uniqueidentifer instead of varchar as data type. Microsoft did not mention how they implement it, there is some speed optimization when you use uniqueIdentifer as the data type.

如果您计划使用GUID,请使用uniqueidentifer而不是varchar作为数据类型。 Microsoft没有提到它们是如何实现的,当您使用uniqueIdentifer作为数据类型时,存在一些速度优化。

To use GUID as primary key without sacrificing speed of integer, make the GUID value sequential. Define uniqueidentifer data type as PK, set the default to NEWSEQUENTIALID().

要在不牺牲整数速度的情况下将GUID用作主键,请使GUID值顺序。将uniqueidentifer数据类型定义为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成本作为主键。