[c#] C# guid and SQL uniqueidentifier

I want to create a GUID and store it in the DB.

In C# a guid can be created using Guid.NewGuid(). This creates a 128 bit integer. SQL Server has a uniqueidentifier column which holds a huge hexidecimal number.

Is there a good/preferred way to make C# and SQL Server guids play well together? (i.e. create a guid using Guid.New() and then store it in the database using nvarchar or some other field ... or create some hexidecimal number of the form that SQL Server is expecting by some other means)

This question is related to c# sql guid uniqueidentifier

The answer is


// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(GentEFONRFFConnection);
myConnection.Open();
SqlCommand myCommand = new SqlCommand("your Procedure Name", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.Add("@orgid", SqlDbType.UniqueIdentifier).Value = orgid;
myCommand.Parameters.Add("@statid", SqlDbType.UniqueIdentifier).Value = statid;
myCommand.Parameters.Add("@read", SqlDbType.Bit).Value = read;
myCommand.Parameters.Add("@write", SqlDbType.Bit).Value = write;
// Mark the Command as a SPROC

myCommand.ExecuteNonQuery();

myCommand.Dispose();
myConnection.Close();

Store it in the database in a field with a data type of uniqueidentifier.


You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

Your method may look like this (provided that your only parameter is the Guid):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

See also: SQL Server's uniqueidentifier


Here's a code snippet showing how to insert a GUID using a parameterised query:

    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        conn.Open();
        using(SqlTransaction trans = conn.BeginTransaction())
        using (SqlCommand cmd = conn.CreateCommand())
        {
            cmd.Transaction = trans;
            cmd.CommandText = @"INSERT INTO [MYTABLE] ([GuidValue]) VALUE @guidValue;";
            cmd.Parameters.AddWithValue("@guidValue", Guid.NewGuid());
            cmd.ExecuteNonQuery();
            trans.Commit();
        }
    }

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to guid

What is the default value for Guid? A TypeScript GUID class? Generate a UUID on iOS from Swift How to set null to a GUID property Check if Nullable Guid is empty in c# How to create a GUID in Excel? Guid.NewGuid() vs. new Guid() What are the best practices for using a GUID as a primary key, specifically regarding performance? Guid is all 0's (zeros)? How to test valid UUID/GUID?

Examples related to uniqueidentifier

How to get a unique device ID in Swift? How to generate and manually insert a uniqueidentifier in sql server? Generate a unique id How to choose the id generation strategy when using JPA and Hibernate Convert NULL to empty string - Conversion failed when converting from a character string to uniqueidentifier .NET Short Unique Identifier Auto increment in MongoDB to store sequence of Unique User ID Is Secure.ANDROID_ID unique for each device? Hash function that produces short hashes? How to delete from select in MySQL?