数据库SQLServer性能优化之主键选择总结

数据库SQLServer性能优化之主键选择总结

2023年7月13日发(作者:)

数据库SQLServer性能优化之主键选择总结常见的数据库主键选取⽅式有:

●⾃动增长字段

●Uniqueidentifier

●“COMB(Combine)”类型

1、⾃动增长字段

优点:

(1)简单、效率⾼。

缺点:

(1)⾃增⼀般使⽤int型,有数据条数的限制。

(2)在数据库进⾏数据合并时会⽐较⿇烦。

2、GUID

优点:

(1)安全,保证唯⼀性。

(2)不会产⽣⾃增字段那样数据合并时的问题。

缺点:

(1)它的长度是16字节,占⽤⼤量存储空间。

(2)该数据类型毫⽆规律,要在上⾯建⽴索引很耗时,所以效率要⽐使⽤⾃增字段低。3、COMB

考虑到上⾯两种主键类型的优缺点,这⾥使⽤COMB类型可以为两者找到了⼀个平衡点。它的设计思路是这样的:既然GUID类型⽆规律可⾔造成索引效率低下,影响系统的性能,那么能不能通过组合的⽅式,保留GUID前10个字节,⽤后6个字节表⽰GUID⽣成的时间,这样即保证了唯⼀性同时增加了有序性,以此来提⾼索引效率。后6字节的时间精度可以达到1/300秒,两个COMB类型数据完全相同的可能性是在这1/300秒内⽣成的两个GUID前10个字节完全相同,这⼏乎是不可能的。(1)SQL Server中SQL命令实现这⼀思路的⽅式:DECLARE @aGuid UNIQUEIDENTIFIER

SET @aGuid = CAST(CAST(NEWID() AS BINARY(10))+ CAST(GETDATE() AS BINARY(6)) AS UNIQUEIDENTIFIER)(2)实现COMB数据的C#⽅式:///

/// 返回 GUID ⽤于数据库操作,特定的时间代码可以提⾼检索效率/// /// COMB (GUID 与时间混合型) 类型 GUID 数据public static Guid NewComb()

{

byte[] guidArray = d().ToByteArray();

DateTime baseDate = new DateTime(1900,1,1);

DateTime now = ;

// Get the days and milliseconds which will be used to build the byte string

TimeSpan days = new TimeSpan( - );

TimeSpan msecs = new TimeSpan( - (new DateTime(, , ).Ticks));

// Convert to a byte array

// Note that SQL Server is accurate to 1/300th of a millisecond so we divide by 3.333333

byte[] daysArray = es();

byte[] msecsArray = es((long)(illiseconds/3.333333));

// Reverse the bytes to match SQL Servers ordering

e(daysArray);

e(msecsArray);

// Copy the bytes into the guid

(daysArray, - 2, guidArray, - 6, 2);

(msecsArray, - 4, guidArray, - 4, 4);

return new (guidArray);

}

///

/// 从 SQL SERVER 返回的 GUID 中⽣成时间信息/// /// 包含时间信息的 COMB /// 时间public static DateTime GetDateFromComb( guid)

{

DateTime baseDate = new DateTime(1900,1,1);

byte[] daysArray = new byte[4];

byte[] msecsArray = new byte[4];

byte[] guidArray = Array();

// Copy the date parts of the guid to the respective byte arrays.

(guidArray, - 6, daysArray, 2, 2);

(guidArray, - 4, msecsArray, 0, 4);

// Reverse the arrays to put them into the appropriate order

e(daysArray);

e(msecsArray);

// Convert the bytes to ints

int days = 32(daysArray, 0);

int msecs = 32(msecsArray, 0);

DateTime date = s(days);

date = liseconds(msecs * 3.333333);

return date;

}

发布者:admin,转转请注明出处:http://www.yc00.com/xiaochengxu/1689244933a225563.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信