Sending null parameters to Sql Server

Cameron Tinker picture Cameron Tinker · Sep 23, 2013 · Viewed 25.5k times · Source

I have a SqlCommand object that I'm using to update a database table but it doesn't interpret my null values correctly.

Here is the SQL:

UPDATE dbo.tbl 
SET param1 = @param1, 
param2 = @param2,
param3 = @param3,
param4 = @param4, 
param5 = @param5, 
param6 = @param6, 
param7 = @param7, 
param8 = @param8, 
param9 = @param9, 
param10 = @param10 
WHERE param11 = @param11

I have tried null coalescing parameters that are nullable like this, but I haven't had any success. Unless otherwise noted, all parameters are strings:

command.Parameters.AddWithValue("@param1", param1 ?? DBNull.Value);
command.Parameters.AddWithValue("@param2", param2 ?? DBNull.Value);
command.Parameters.AddWithValue("@param3", param3 ?? DBNull.Value);
command.Parameters.AddWithValue("@param4", param4 ?? DBNull.Value);
command.Parameters.AddWithValue("@param5", param5 ?? DBNull.Value);
// param6 is nullable type DateTime?
command.Parameters.AddWithValue("@param6", param6 ?? DBNull.Value); 
command.Parameters.AddWithValue("@param7", param7 ?? DBNull.Value);
// param8 is nullable type DateTime?
command.Parameters.AddWithValue("@param8", param8 ?? DBNull.Value); 
command.Parameters.AddWithValue("@param9", param9 ?? DBNull.Value);
// param10 nullable type float?
command.Parameters.AddWithValue("@param10", param10 ?? DBNull.Value); 
command.Parameters.AddWithValue("@param11", param11 ?? DBNull.Value);

I get an exception like this:

The parameterized query '(@param1 nvarchar(4000),@param2 nvarchar(4000),@param3 nvarc' expects the parameter '@param4', which was not supplied.

I've also tried looping through each parameter after they've been added to the SqlCommand object to set DbNull.Value if the parameter value is null like this:

foreach (SqlParameter parameter in command.Parameters)
{
    if (parameter.Value == null)
    {
        parameter.Value = DBNull.Value;
    }
}

However, this approach is causing the exception:

String or binary data would be truncated.
The statement has been terminated.

What is the best practice for passing null parameters to a SqlCommand? I don't simply want to pass in default values if they're null since the database schema allows null values.

Answer

Gaurav123 picture Gaurav123 · Feb 11, 2014

Try this :

command.Parameters.AddWithValue("@param1", param1 ?? Convert.DBNull);