根据SQL Server排序规则创建顺序GUID

public static class GuidUtil
{
private static readonly long EpochMilliseconds = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks / 10000L;

    /// <summary>
    /// Creates a sequential GUID according to SQL Server's ordering rules.
    /// </summary>
    public static Guid NewSequentialId()
    {
        // This code was not reviewed to guarantee uniqueness under most conditions, nor completely optimize for avoiding
        // page splits in SQL Server when doing inserts from multiple hosts, so do not re-use in production systems.
        var guidBytes = Guid.NewGuid().ToByteArray();

        // get the milliseconds since Jan 1 1970
        byte[] sequential = BitConverter.GetBytes((DateTime.Now.Ticks / 10000L) - EpochMilliseconds);

        // discard the 2 most significant bytes, as we only care about the milliseconds increasing, but the highest ones 
        // should be 0 for several thousand years to come (non-issue).
        if (BitConverter.IsLittleEndian)
        {
            guidBytes[10] = sequential[5];
            guidBytes[11] = sequential[4];
            guidBytes[12] = sequential[3];
            guidBytes[13] = sequential[2];
            guidBytes[14] = sequential[1];
            guidBytes[15] = sequential[0];
        }
        else
        {
            Buffer.BlockCopy(sequential, 2, guidBytes, 10, 6);
        }

        return new Guid(guidBytes);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值