ASP.NET无法将参数值从String转换为DateTime

时间:2016-06-08 13:38:19

标签: c# asp.net

我将数据插入到数据库存储过程中,如下所示:

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

4 个答案:

答案 0 :(得分:2)

您可能需要考虑在将日期作为参数传递之前显式解析日期,并检查它是否包含一个值,以确定是否应传递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);

答案 1 :(得分:0)

检查空字符串并替换DBNull.Value。

parameter2.Value = string.IsNullOrWhiteSpace(sortedCells[i].finishedDate) 
    ? DBNull.Value 
    : sortedCells[i].finishedDate;

或者,在存储过程定义中为参数指定一个默认值NULL,然后仅在值不为空时设置该值。

对于存储过程:

CREATE PROCEDURE [YourSchema].[YourProcedure]
...snip...
@actualFinish DATETIME = NULL
...snip...

然后:

if(!String.IsNullOrWhiteSpace(sortedCells[i].finishedDate)
    parameter2.Value = sortedCells[i].finishedDate;

编辑添加:

使用可空的DateTime会更清楚,我想,然后让隐式字符串转换做它的事情。

DateTime? finishedDate = null;
if(!String.IsNullOrWhiteSpace(sortedCells[i].finishedDate))
        finishedDate = DateTime.Parse(sortedCells[i].finishedDate);

然后,finishedDate始终是您的参数值。使用TryParse可以更安全,并在日期解析失败时通知用户。但是,TryParse不会采用可空类型,因此您可以使用两个变量,或者您可以使用常规DateTime变量并使用DateTime.Min作为"没有日期"的标记值。并使用三元运算符将其切换为null。有很多方法可以给这只猫上皮。

答案 2 :(得分:0)

在传递值之前,应始终将其转换为正确的类型。

var actualFinishParameter = new SqlParameter("@actualFinish", SqlDbType.DateTime);
Object actualFinish = DBNull.Value;
DateTime finishDate;
if(DateTime.TryParse(sortedCells[i].finishedDate, out finishDate))
    actualFinish = finishDate;
actualFinishParameter.Value = actualFinish;
command.Parameters.Add(actualFinishParameter);

答案 3 :(得分:0)

在相应的表中,将NULL添加到相应的日期列。

[FinishedDate] [datetime] NULL。

希望这会奏效。