poz2k4444
poz2k4444

Reputation: 270

Parameterized query which sends NULL value, with C# and SQL Server

I tried to pass some variables into a parameterized query but when the value is NULL it throws an exception that says the value is not provided.

How can I fix that without an if or something like that?

My code is this

var cmdPersona_Log = new SqlCommand();
cmdPersona_Log.Parameters.Clear();
cmdPersona_Log.Connection = mySqlConnection;
cmdPersona_Log.CommandType = CommandType.Text;
cmdPersona_Log.CommandText = @"INSERT INTO [Tomin].[TominRH].[Persona_Log] "
+ "([Id_Action],[Id_User],[Id_Date],[Id_Entidad],[Nombre],[Paterno],[Materno],[Sexo],[Id_Nacionalidad])"
+ " Values (1, 'Admin', @fecha, @id_entidad, @nombre, @paterno, @materno, 1, 52)";

cmdPersona_Log.Parameters.Add("@fecha", DateTime.Now);
cmdPersona_Log.Parameters.Add("@id_entidad", dbRow["CUENTA"]);
cmdPersona_Log.Parameters.Add("@nombre", nombre);
cmdPersona_Log.Parameters.Add("@paterno", paterno);
cmdPersona_Log.Parameters.Add("@materno", materno);

cmdPersona_Log.ExecuteNonQuery();

Upvotes: 0

Views: 1976

Answers (1)

Claudio Redi
Claudio Redi

Reputation: 68400

I will assume that your problem is that the underlying field doesn't support nulls. If this is the case, you could do something like this

cmdPersona_Log.Parameters.Add("@nombre", nombre ?? string.Empty);
cmdPersona_Log.Parameters.Add("@paterno", paterno ?? string.Empty); 
cmdPersona_Log.Parameters.Add("@materno", materno ?? string.Empty);

You'll be inserting an empty string in case you have a null using the null-coalescing operator.

Upvotes: 3

Related Questions