简体   繁体   中英

How can I insert a null value into Sql Server date column using asp.net and command parameters

I have the following code:

SqlDateTime sqldatenull = SqlDateTime.Null; 
sSql = "INSERT INTO mydb.dbo.myTable(FromPeriod) Values (@FromPeriod)";

if (sFromPeriod.Length == 0) {
    cmd.Parameters.Add("@FromPeriod", SqlDbType.DateTime);
    cmd.Parameters["@FromPeriod"].Value = sqldatenull;
} else {
    cmd.Parameters.AddWithValue("@FromPeriod", sTempFromPeriod);
}

cmd.ExecuteNonQuery();

sFromPeriod is a date and when it's length is zero, I receive error: Conversion failed when converting date and/or time from character string. When sFromPeriod has a value, the code works fine. I have also used DBNull.Value in place of sqldatenull and received the same error. What am I missing?

Consider using DBNull.Value instead of SqlDateTime.Null .

For example:

cmd.Parameters["@FromPeriod"].Value = DBNull.Value;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM