我正在尝试将新的DateTime 2013-09-22传递给以下内容,但是它显示我的sql语法中存在错误。 有什么想法吗?
DateTime WeekEnding = new DateTime(2013, 9, 22);
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(
@"select WeekEnding, sum(Total) as Total " +
"from Data where WeekEnding = '@WeekEnding' " +
"group by WeekEnding",
myConnection);
myCommand.Parameters.Add("@WeekEnding", SqlDbType.DateTime);
myCommand.Parameters["@WeekEnding"].Value = WeekEnding;
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine("Combined : " + myReader["Total"].ToString());
}
答案 0 :(得分:1)
您需要删除参数周围的引号。即使在sql字符串中引用了实际数据的表示,参数也始终不加引号。
在旁注中,请考虑使用-block为您的IDisposable数据库对象,如SqlDataReader,SqlCommand等。
答案 1 :(得分:0)
无需将参数括在单引号中,没有它就可以使用。
此外,在处理日期时,您必须记住DateTime
对象具有日期和时间组件,因此最好一起使用>=
和<=
,除非您确定数据库中的字段始终将时间组件设置为午夜。
试试这个:
DateTime WeekEnding = new DateTime(2013, 9, 22);
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand(
@"select WeekEnding, sum(Total) as Total " +
"from Data where WeekEnding >= @WeekEnding AND WeekEnding <= @WeekEnding" +
"group by WeekEnding",
myConnection);
myCommand.Parameters.Add("@WeekEnding", SqlDbType.DateTime);
myCommand.Parameters["@WeekEnding"].Value = WeekEnding;
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine("Combined : " + myReader["Total"].ToString());
}
答案 2 :(得分:0)
从查询中删除'@WeekEnding'
周围的引号。查询文本应该是这样的:
@"select WeekEnding, sum(Total) as Total " +
"from Data where WeekEnding = @WeekEnding " +
"group by WeekEnding",
答案 3 :(得分:-1)
您可以使用String.Format()方法来实现您的目标。
例如:
string query = @"select WeekEnding, sum(Total) as Total
from Data where WeekEnding = {0}
group by WeekEnding";
string sql = String.Format(query,WeekEnding);
//then
SqlCommand myCommand = new SqlCommand(sql , myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine("Combined : " + myReader["Total"].ToString());
}
希望这有帮助。