带有日期分隔符的 C# 和 MS Access SQL

问题描述

我遇到了这个查询错误

"SELECT COUNT(*) AS x FROM accounts_info ";
        query += "INNER JOIN customers_info ON accounts_info.cust_code = customers_info.cust_code ";
        query += "WHERE accounts_info.date_due >= #@a# AND accounts_info.is_paid = 0";

OleDbCommand cmd = new OleDbCommand(query,con);
String aaa = DateTime.Now.ToString("MM/dd/yyyy");
cmd.Parameters.AddWithValue("@a",aaa);

哪个错误告诉我:附加信息:查询表达式“accounts_info.date_due >= #@a# AND accounts_info.is_paid = 0”中的日期语法错误

是否可以在日期分隔符 #1/13/2021# 中插入参数,例如 #@param@#

解决方法

两件事

  • 删除#
  • 使参数值成为日期而不是字符串

喜欢...

"SELECT COUNT(*) AS x FROM accounts_info ";
    query += "INNER JOIN customers_info ON accounts_info.cust_code = customers_info.cust_code ";
    query += "WHERE accounts_info.date_due >= @a AND accounts_info.is_paid = 0";

OleDbCommand cmd = new OleDbCommand(query,con);
cmd.Parameters.AddWithValue("@a",DateTime.Now.Date); //.Date will remove time portion from date

附注..

OLEDB 不处理命名参数。您可以将它们与名称放在一起,但您提供的名称无关紧要,重要的是顺序.. 参数集合必须包含相同数量的参数,并且与它们在 SQL 中出现的顺序相同。出于这个原因,并且为了不至于认为参数名称可以在查询中多次重复使用,有些人使用 ?参数占位符的标记

"SELECT COUNT(*) AS x FROM accounts_info ";
    query += "INNER JOIN customers_info ON accounts_info.cust_code = customers_info.cust_code ";
    query += "WHERE accounts_info.date_due >= ? AND accounts_info.is_paid = 0";

OleDbCommand cmd = new OleDbCommand(query,con);
cmd.Parameters.AddWithValue("p1",DateTime.Now.Date);
,

您的查询在下面给出您的查询。

SELECT COUNT(*) AS x FROM accounts_info
INNER JOIN customers_info ON accounts_info.cust_code = customers_info.cust_code
WHERE accounts_info.date_due >= #@a# AND accounts_info.is_paid = 0

所以请从查询中删除 #

另外请创建一个存储过程并传递参数,而不是在代码中编写查询。