Sequential GUID are Unique

This post refers to the previous post, where liviu warns against the non uniqueness of T-SQL sequential guid. The technique used is based on the UuidCreateSequential API function of the operating system. This function generates unique guid unless there is no NetworkCard in the system, but this function warns you when the guid can be considered unique only on local machine, when it returns the value RPC_S_UUID_LOCAL_ONLY.

image

This happens when the machine has not network card, and this is not a problem in my scenario, but if this is something you fear, you can simply change the function in this way.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static class SequentialGuidGenerator
{
private const Int32 RPC_S_OK = 0x0;
 
/// <summary>
/// Questa funzione di sistema presa dalla dll rpcrt4.dll permette di generare
/// Guid sequenziali che sono più ottimali per inserimenti massivi di grandi quantità 
/// di dati in database in cui l'indice cluster è messo sull'id
/// </summary>
/// <param name="guid"></param>
/// <returns></returns>
[DllImport("rpcrt4.dll", SetLastError = true)]
internal static extern int UuidCreateSequential(out Guid guid);
 
public static Guid CreateSequentialGuid()
{
Guid guid;
Int32 retvalue = UuidCreateSequential(out guid);
if (retvalue != RPC_S_OK)
{
//it is not safe to generate a guid on this machine because it would be unique
//only in this machine
return Guid.NewGuid();
}
return guid;
}
 
}

The change is in link 19, I check for the retvalue and if it is different from RPC_S_OK I use the standard Guid generator. This little change makes me sure that if the machine could not generate unique sequential guid, it uses standard guid generation avoiding the risk of having two identical GUID.

alk.