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

时间:2021-12-09 16:02:52
 public static class GuidUtil
{
private static readonly long EpochMilliseconds = new DateTime(, , , , , , 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[] = sequential[];
guidBytes[] = sequential[];
guidBytes[] = sequential[];
guidBytes[] = sequential[];
guidBytes[] = sequential[];
guidBytes[] = sequential[];
}
else
{
Buffer.BlockCopy(sequential, , guidBytes, , );
} return new Guid(guidBytes);
}
}