Sunday, May 10, 2009

Unique Identifier In .Net & SQL

A GUID (Globally Unique Identifiers) is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required. Such an identifier has a very low probability of being duplicated. In the .NET framework the System.Guid.NewGuid method is used to generate the unique identifiers.

System.Guid desiredGuid = System.Guid.NewGuid();

This desiredGuid can be directly save to DB. The data type of the filed should be “uniqueidentifier” or we can cast it as string …. And also we can store GUID in “System.Guid” data type variable(C#).

convert GUID to Sting

System.Guid desiredGuid = System.Guid.NewGuid();
string a=desiredGuid.ToString();

convert a string to a GUID

Guid MyGuid = new Guid(stringValue);

In SQL Server, the “uniqueidentifier” data type is used to store the GUIDs and newid() function will generate GUID.