考试网 >> IT认证 >> 水平 >> 系统工程师 >> 小议数据库主键选取策略

小议数据库主键选取策略

发布时间:2006-06-28 02:23     点击:
分页:上一页  1 2 3 [4] 5  下一页

SET @aGuid = CAST(CAST(NEWID() AS BINARY(10))

+ CAST(GETDATE() AS BINARY(6)) AS UNIQUEIDENTIFIER)

  经过测试,使用COMB做主键比使用INT做主键,在检索、插入、更新、删除等操作上仍然显慢,但比Unidentifier类型要快上一些。关于测试数据可以参考我2004年7月21日的随笔。

  除了使用存储过程实现COMB数据外,我们也可以使用C#生成COMB数据,这样所有主键生成工作可以在客户端完成。C#代码如下:

/**////<summary>

/// 返回 GUID 用于数据库操作,特定的时间代码可以提高检索效率

/// </summary>

/// <returns>COMB (GUID 与时间混合型) 类型 GUID 数据</returns>

public static Guid NewComb()

{

byte[] guidArray = System.Guid.NewGuid().ToByteArray();

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

DateTime now = DateTime.Now;

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

TimeSpan days = new TimeSpan(now.Ticks - baseDate.Ticks);

TimeSpan msecs = new TimeSpan(now.Ticks - (new DateTime(now.Year, now.Month, now.Day).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 = BitConverter.GetBytes(days.Days);

byte[] msecsArray = BitConverter.GetBytes((long)(msecs.TotalMilliseconds/3.333333));

// Reverse the bytes to match SQL Servers ordering

Array.Reverse(daysArray);

Array.Reverse(msecsArray);

// Copy the bytes into the guid

Array.Copy(daysArray, daysArray.Length - 2, guidArray, guidArray.Length - 6, 2);

Array.Copy(msecsArray, msecsArray.Length - 4, guidArray, guidArray.Length - 4, 4);

return new System.Guid(guidArray);

}

分页:上一页  1 2 3 [4] 5  下一页
版权申明:未经书面授权请勿转载本站信息!!作品版权归所属媒体与作者所有!!
发表评论: 匿名发表 用户名: 查看评论
您将承担一切因您的行为、言论而直接或间接导致的民事或刑事法律责任
留言板管理人员有权保留或删除其管辖留言中的任意内容
本站提醒:不要进行人身攻击。谢谢配合。
在本站搜索相关信息
2003-2005 Ksw123.com All Rights Reserved. - TOP
Copyright © 2006 Ksw123.com. All rights reserved.中国考题网 版权所有