【发布时间】: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