我正在将数据插入数据库存储过程中,如下所示:
SqlParameter parameter2 = new SqlParameter("@actualFinish", SqlDbType.DateTime);
parameter2.Value = sortedCells[i].finishedDate;
parameter2.Direction = ParameterDirection.Input;
command.Parameters.Add(parameter2);
我遇到的问题是当我尝试插入一个空日期时出现""
此错误:
Failed to convert parameter value from a String to a DateTime
我要插入的列可以允许NULL ....所以我要怎么说,如果这是""
给它一个NULL
您可能需要考虑在将日期作为参数传递之前显式解析日期,并进行检查以查看其是否包含值,以确定是否应该传递DateTime
对象或DBNull.Value
:
DateTime finishDate = DateTime.MinValue;
// This will attempt to parse the value if possible
DateTime.TryParse(sortedCells[i].finishedDate, out finishDate);
// Build your parameter here
SqlParameter parameter2 = new SqlParameter("@actualFinish", SqlDbType.DateTime);
parameter2.Direction = ParameterDirection.Input;
// If you are using a nullable field, you may want to explicitly indicate that
parameter2.IsNullable = true;
// Then when setting the value, check if you should use the value or null
if(finishDate == DateTime.MinValue)
{
parameter2.Value = DBNull.Value;
}
else
{
parameter2.Value = finishDate;
}
// Finally add your parameter
command.Parameters.Add(parameter2);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句