C # guid and SQL uniqueidentifier

I want to create a GUID and save it to the database.

In C #, a directive can be created using Guid.NewGuid (). This creates a 128 bit integer. SQL Server has a uniqueidentifier column that contains a huge hexadecimal number.

Is there a good / preferred way to make C # and SQL Server commands work well together? (i.e. create a manual using Guid.New (), and then save it to the database using nvarchar or some other field ... or create some kind of hexadecimal form number expected by SQL Server in other ways)

+53
c # sql guid uniqueidentifier
Sep 16 '09 at 22:47
source share
5 answers

SQL expects a GUID as a string. The next one in C # returns the Sql string waiting.

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

Something like

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

is what SQL should look like.

+46
Sep 16 '09 at 10:50
source share

Here's the snipit code showing how to embed Guid using a parameterized 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(); } } 
+53
Sep 16 '09 at 23:16
source share

You can pass the C # Guid value directly to the SQL stored procedure by specifying SqlDbType .UniqueIdentifier .

Your method might look like this (assuming your only parameter is 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 uniqueidentifier

+5
Feb 17 '11 at 18:49
source share

Save it in the database in the field with the uniqueidentifier data type.

+4
Sep 16 '09 at 22:51
source share
 // 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(); 
0
Apr 11 2018-12-12T00:
source share



All Articles