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#⽅式:///
{
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);
}
///
{
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条)