我知道在SQL中此日期范围之间存在记录,但是我尝试了各种格式,甚至使范围更大,但这仍然不会返回结果。我在此查询中做错了什么,导致没有记录被返回?谢谢您的帮助。
DateTime today = DateTime.Now;
DateTime tomorrow = today.AddDays(1);
DateTime yesterday = today.AddDays(-1);
DateTime dt = DateTime.Now;
string yesterdayString = yesterday.ToString("yyyy-MM-dd HH:mm:ss");
string tomorrowString = tomorrow.ToString("yyyy-MM-dd HH:mm:ss");
int itemNum = 0;
string query = "select DocID, CNo, DocType, DocNumber from errordata where cno = '" + cno + "' and createddate > '" + yesterdayString + "' and createddate < '" + tomorrowString + "' order by '" + sorton + "'desc";
最佳答案
您可以尝试以下操作:
string query = "SELECT DocID, CNo, DocType, DocNumber "+
"FROM tableName "+
"WHERE cno = @cno AND "+
"CreatedDate BETWEEN @yesterday AND @tomorrow";
var sqlCommand = new SqlCommand(query, connectionString);
sql.Parameters.Add("@cno", cno);
sql.Parameters.Add("@yesterday", yesterday);
sql.Parameters.Add("@tomorrow", tomorrow);
我认为您的问题是缺少
FROM
。此外,我使用参数编写了查询,以防止sql注入。