81

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)

1
  • 22
    Do NOT use nvarchar, use uniqueidentifier. Commented Sep 16, 2009 at 22:55

5 Answers 5

73

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();
        }
    }
Sign up to request clarification or add additional context in comments.

4 Comments

guidValue should be @guidValue
+1 for demonstrating the correct way to do it, rather than just answering the question literally.
Very useful. I was trying to parse a string etc... inside the database. This works great. Cheers, ~ck
This works for inserting but not for a WHERE clause. It tries to compare the lowercase guid from c# to the uppercase uniqueidentifier and that doesn't match.
61

SQL is expecting the GUID as a string. The following in C# returns a string Sql is expecting.

"'" + Guid.NewGuid().ToString() + "'"

Something like

INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')

is what it should look like in SQL.

4 Comments

If you use SqlParameter, you don't have to convert the GUID into a string.
To be clearer to everyone, I'm not suggesting that the sql specified should be used as demonstrated from C# with string concatenation. The crux of the question, I believe, is what form does a SQL UNIQUEIDENTIFIER LITERAL look like. The literal looks just like a string but with a special format. The two code snippets demonstrate what the literal looks like in 2 languages. I agree with DLKG that using a parameterized query and passing the guid as a typed parameter is both more performant as well as preventing potential SQL Injection attacks.
And in Entity Framework, Database first method, a uniqueidentifier SQL datatype (recommended in comment by @TorHaugen) translates to a System.Guid C# datatype, which is what OP asked about
so how does System.Guid generates an identifier that is not already in the DB ? although, the odds would be small...is there a check for uniqueness ?
12

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):

int StoreGuid(Guid guid)
{
  using SqlConnection connection = new("YourDataBaseConnectionString");
  using SqlCommand command = new() {
    Connection = connection ,
    CommandType = CommandType.StoredProcedure,
    CommandText = "StoreGuid",
    Parameters = {
      new() {
        ParameterName = "@guid",
        SqlDbType = SqlDbType.UniqueIdentifier, // right here
        Value = guid
      }
    }
  };
  connection.Open();
  return command.ExecuteNonQuery();    
}

See also: SQL Server's uniqueidentifier

Comments

5

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

Comments

2
// 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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.