从代码将存储过程中的数据类型 nvarchar 转换为日期时间时出错



从 C# 调用存储过程时出现以下错误。

参数在代码中定义为:

 if (repRIS.Length > 0)
    command.Parameters.AddWithValue("@repRIS", repRIS);
 else
    command.Parameters.AddWithValue("@repRIS", DBNull.Value);
  command.Parameters.Add("@invDt", OleDbType.Date).Value = invDate;

我已经注释掉了存储过程中的所有内容,现在只有以下内容:

ALTER PROCEDURE [dbo].[SearchDates]
    -- Add the parameters for the stored procedure here
     @invDt datetime,
     @repRIS varchar(10) ,
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
select this, that, and, the, other from myTableName ird
where
     ird.RIS = COALESCE(@repRIS, ird.RIS) 
     and ird.InventoryDate = @invDt
END

清单日期在数据库中的类型为日期时间。

当我从SQL MS运行SP时,它产生的结果没有问题,但是,当使用应用程序调用它时,我收到以下错误消息

将数据类型 nvarchar 转换为日期时间时出错

我注意到它在我从SQLConnection切换到OLEDBConnection之后开始发生。我尚未确认这一点。(我不得不切换以符合应用程序其余部分在我之前编写的方式)

更新:当我在文本框中输入 9/30/2018 的值时,它被传递到存储过程中,如下所示: 转换为日期时间后{9/30/2018 12:00:00 AM}(上面的代码)

使用 OleDb 时,应始终记住,参数不是根据其名称传递的,而是按照它们添加到参数集合的确切顺序传递的。

在代码中,首先添加@repRIS,这是传递给 SP 的第一个参数。但是 SP 需要第一个参数的日期,而您会收到异常

您需要更改参数集合中的插入顺序或切换 SP 中参数的声明顺序

command.Parameters.Add("@invDt", OleDbType.Date).Value = invDate;     
if (repRIS.Length > 0)
    command.Parameters.AddWithValue("@repRIS", repRIS);
else
    command.Parameters.AddWithValue("@repRIS", DBNull.Value);

另一件事是看看这篇文章,我们可以停止使用AddWithValue吗?

我会说 Min Date 在 C# 的 SQL 中不起作用,因为最小 C# 日期时间和 SQL 支持的日期时间和 SQL 支持的日期是不同的。

用:

System.Data.SqlTypes.SqlDateTime.MinValue.Value

而是 C# 日期时间提供的最小值。这应该有效

最新更新