Search code examples
c#sqldatetimeinsertparameterized-query

How to insert null value in Database through parameterized query


I have a datetime datatype : dttm

Also the database field type is datatime

Now I am doing this:

if (dttm.HasValue)
{
    cmd.Parameters.AddWithValue("@dtb", dttm);
}
else
{
    // It should insert null value into database
    // through cmd.Parameters.AddWithValue("@dtb", _____)
}

How can this be done.


Solution

  • Use DBNull.Value

    if (dttm.HasValue)
    {
        cmd.Parameters.AddWithValue("@dtb", dttm);
    }
    else
    {
        cmd.Parameters.AddWithValue("@dtb", DBNull.Value)
    }