2016-06-08 56 views
1

我将数据插入到数据库中的存储过程,像这样:ASP.NET无法参数值从字符串转换为datetime

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

+0

使用三元运算符。类似于parameter2.Value =(!sortedCells [i] .finishedDate,Equals(string.Empty)?sortedCells [i] .finishedDate:DBNull.Value; –

回答

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); 
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? finishedDate = null; 
if(!String.IsNullOrWhiteSpace(sortedCells[i].finishedDate)) 
     finishedDate = DateTime.Parse(sortedCells[i].finishedDate); 

然后finishedDate始终是您的参数值。通过使用TryParse并在日期解析失败时通知用户,您甚至可以更安全。尽管TryParse不会使用可为空的类型,所以您可以使用两个变量,也可以使用常规的DateTime变量,并将DateTime.Min用作“no date”的标记值,并使用三元运算符将其切换为null。许多方法来剥皮这只猫。

+0

我试过'parameter2.Value = string.IsNullOrWhiteSpace(sortedCells [i]。已完成日期) ?DBNull.Value :sortedCells [i] .finishedDate;'并得到此错误'无法确定条件表达式的类型,因为在System.DBNull和字符串之间没有隐式转换' – user979331

+0

啊,将DBNull强制转换为参数(string)DBNull.Value。我通常在SP中使用默认参数值,而不是显式传入null。 –

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); 
0

在适当的表中,将NULL添加到适当的日期列。

[FinishedDate] [datetime] NULL。

希望这会起作用。

相关问题