C # guid 和 SQL unique 标识符

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

在 C # 中,可以使用 Guid 创建 Guid。NewGuid ().这将创建一个128位整数。SQLServer 有一个 uniqueIdentity 列,其中包含一个巨大的十六进制数。

有没有一种好的/首选的方法可以让 C # 和 SQLServer 指南很好地结合在一起?(例如,使用 Guid 创建一个 Guid。New () ,然后使用 nvarchar 或其他字段将其存储在数据库中... ... 或者通过其他方式创建 SQL Server 期望的表单的十六进制数)

156043 次浏览

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.

Store it in the database in a field with a data type of 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();
}
}

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

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