从代码在存储过程中将数据类型 nvarchar 转换为 datetime 时出错

Error converting data type nvarchar to datetime in a Stored Procedure from code

从 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

InventoryDate 是数据库中的 DateTime 类型。

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

Error converting data type nvarchar to datetime

我注意到它在我从 SQLConnection 切换到 OLEDBConnection 后开始发生。我还没有证实这一点。 (我不得不切换以遵守在我之前编写的应用程序的其余部分)

更新: 当我在文本框中输入 9/30/2018 的值时,它被传递到存储过程中:{9/30/2018 12:00:00 AM} after converting to datetime (code above)

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

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

您需要更改Parameters集合中的插入顺序或切换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);

还有一件事就是看看这篇文章Can we stop using AddWithValue already?

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

使用:

System.Data.SqlTypes.SqlDateTime.MinValue.Value

而不是 C# Datetime 提供的最小值。 这应该有效