C # guid e SQL uniqueidentifier
-
07-07-2019 - |
Domanda
Voglio creare un GUID e memorizzarlo nel DB.
In C # un guid può essere creato usando Guid.NewGuid (). Questo crea un numero intero a 128 bit. SQL Server ha una colonna uniqueidentifier che contiene un numero esadecimale enorme.
C'è un modo buono / preferito per far giocare bene le guide C # e SQL Server? (ad es. creare un guid usando Guid.New () e poi memorizzarlo nel database usando nvarchar o qualche altro campo ... o creare un numero esadecimale del modulo che SQL Server si aspetta in qualche altro modo)
Soluzione
SQL si aspetta il GUID come una stringa. Quanto segue in C # restituisce una stringa che Sql si aspetta.
"'" + Guid.NewGuid().ToString() + "'"
Qualcosa di simile
INSERT INTO TABLE (GuidID) VALUE ('4b5e95a7-745a-462f-ae53-709a8583700a')
è come dovrebbe apparire in SQL.
Altri suggerimenti
Ecco uno snippet di codice che mostra come inserire un Guid usando una query con parametri:
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();
}
}
È possibile passare un valore Guid C # direttamente a una stored procedure SQL specificando SqlDbType .UniqueIdentifier
.
Il tuo metodo potrebbe assomigliare a questo (a condizione che il tuo unico parametro sia il 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();
}
}
Vedi anche: uniqueidentifier
Conservalo nel database in un campo con un tipo di dati di 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();