【问题标题】:Passing DateTime in the where class as a parameter C#在 where 类中传递 DateTime 作为参数 C#
【发布时间】:2016-08-04 13:15:44
【问题描述】:

我正在尝试将两个 DateTime 参数传递给 SQL 语句。这就是我试图与 C# 代码一起传递的内容:

string command = @"SELECT EMP._name AS employername, EMP._contact AS employercontact, EMP.employerid, EMP.firmid 
                 FROM EMPLOYER AS EMP 
                 LEFT JOIN SERVICE AS SERV 
                 ON EMP.employerid = SERV.employerid 
                 WHERE SERV._dateRecordCreated >= @yearStartDate 
                 AND SERV._dateRecordCreated  <= @yearEndDate 
                 ORDER BY employername;";

这就是我传递参数的方式:

DateTime yearStartDt = new DateTime(2015, 1,1);
DateTime yearEndDt = new DateTime(2015, 12, 31);

sqlCommand.Parameters.Add("@yearStartDate", yearStartDt);
sqlCommand.Parameters.Add("@yearEndDate", yearEndDt);

我不断收到 SQL 异常 137

【问题讨论】:

  • 删除 SQL 中 @yearStartDate@yearEndDate 周围的引号。这些值不会被替换——不需要字符串引用。
  • @DrewKennedy 这是使用AS 的有效方式。 AS 可以省略,仅说明 FROM EMPLOYER EMP
  • 你有什么理由一直给人们数字而不是消息?错误 137 是“必须声明标量变量 [变量]”。这表明 SQL Server 没有看到您传递参数,这并不奇怪,因为调用仍然是错误的。使用sqlCommand.Parameters.Add("@yearStartDate", SqlDbType.DateTime).Value = yearStartDt
  • 你能展示你的整个代码块吗?正在实例化和打开的连接、SqlCommand 对象等?
  • 你能添加更多与sqlCommand相关的代码

标签: c# .net sql-server tsql sql-server-2012


【解决方案1】:

使用类似的东西

sqlCommand.Parameters.Add("@yearStartDate", SqlDbType.DateTime);
sqlCommand.Parameters["@yearStartDate"].Value = yearStartDt;

【讨论】:

  • 你应该解释为什么这回答了这个问题 - Add 期望一个类型作为第二个参数,不是一个值。它还返回新的 SqlParameter 对象,因此没有理由使用 `["@paramname"] 再次检索它
  • sqlCommand.Parameters.Add("@yearStartDate", SqlDbType.DateTime).Value = yearStartDt;
猜你喜欢
  • 1970-01-01
  • 2015-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-12
  • 2011-05-31
  • 2017-05-30
  • 2021-09-07
相关资源
最近更新 更多