4

I am trying to build some query and insert a list with 7 columns into a SQL table using C#. In my list I have few NULL values for few columns and I am not able to pass them to the following query

string strInsertListToTable = @"INSERT INTO ImpliedOutrightData (id,product,term,bid,offer,bidcp,offercp) VALUES(@id,@product,@term,@bid,@offer,@bidcp,@offercp)";
    for (int i = 0; i < resultList.Count; i++)
        {  


           SqlCommand cmdInsertList = new SqlCommand(strInsertListToTable, sqlcon);

            cmdInsertList.CommandType = CommandType.Text;
            cmdInsertList.Parameters.Clear();
            cmdInsertList.Parameters.AddWithValue("@id", resultList[i].id);
            cmdInsertList.Parameters.AddWithValue("@product", resultList[i].product);
            cmdInsertList.Parameters.AddWithValue("@term", resultList[i].term);
            cmdInsertList.Parameters.AddWithValue("@bid", resultList[i].bid);
            cmdInsertList.Parameters.AddWithValue("@offer", resultList[i].offer);

            cmdInsertList.Parameters.AddWithValue("@bidcp",resultList[i].bidcp);
            cmdInsertList.Parameters.AddWithValue("@offercp", resultList[i].offercp);
            cmdInsertList.ExecuteNonQuery();
        }

While the above query loops I get the error

The parameterized query '(@id int,@product nvarchar(2),@term nvarchar(5),@bid float,@bidc' expects the parameter '@offercp', which was not supplied.
DoIt
  • 3,270
  • 9
  • 51
  • 103

3 Answers3

3

When the value of the parameter is null, you should set the corresponding value to DbNull.Value:

cmdInsertList.Parameters.AddWithValue(
    "@offercp"
,   resultList[i].offercp == null ? (object)DbNull.Value : resultList[i].offercp
);

Note the cast to object - you need this so that both sides of the conditional evaluate to the same type.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
3

You need to use DBNull.Value. I wrote this extension method:

public static SqlParameter AddNullSafe(this SqlParameterCollection parameters, SqlParameter value)
{
    if (value != null)
    {
        if (value.Value == null)
        {
            value.Value = DBNull.Value;
        }
        return parameters.Add(value);
    }
    return null;
}
Slippery Pete
  • 3,051
  • 1
  • 13
  • 15
2

If you suspect a value could be null you can use DBNull to indicate the null value for the parameter:

cmdInsertList.Parameters.AddWithValue("@offercp",
    resultList[i].offercp ?? DBNull.Value);
Kelsey
  • 47,246
  • 16
  • 124
  • 162