0

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();
3
  • What's the field causing troubles? Commented Aug 28, 2012 at 0:15
  • @materno, the thing is, when I do the query without parameters there is no problem, but there will be some times that those parameters will be null Commented Aug 28, 2012 at 0:18
  • you should check if the parameter is != null before add it Commented Aug 28, 2012 at 0:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.