C#guid和SQL uniqueidentifier

我想创build一个GUID并将其存储在数据库中。

在C#中,guid可以使用Guid.NewGuid()创build。 这会创build一个128位的整数。 SQL Server有一个uniqueidentifier列,它包含一个巨大的hex数字。

有没有一个好的/首选的方式,使C#和SQL Server GUID一起玩好? (即使用Guid.New()创build一个GUID,然后使用nvarchar或其他字段将其存储在数据库中…或者通过其他方式创buildSQL Server预期的hex数字)

SQL期待作为一个string的GUID。 以下在C#中返回一个stringSql所期待的。

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

就像是

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

是它应该在SQL中看起来像什么。

这是一个代码片段,展示了如何使用参数化查询插入一个Guid:

  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(); } } 

将其存储在数据库中的数据types为uniqueidentifier的字段中。

您可以通过指定SqlDbType .UniqueIdentifier将C#Guid值直接传递给SQL存储过程。

你的方法可能看起来像这样(假设你唯一的参数是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(); } } 

另请参阅:SQL Server的uniqueidentifier

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