我在“#”附近收到错误语法错误。如何解决这个查询?

问题描述:

cmd = new SqlCommand("SELECT (InvoiceNo) as [Invoice No],(InvoiceDate) as [Invoice Date],(Sales.CustomerID) as [Customer ID],(CustomerName) as [Customer Name],(GrandTotal) as [Grand Total],(TotalPayment) as [Total Payment],(PaymentDue) as [Payment Due] from Sales,Customer where Sales.CustomerID=Customer.CustomerID and InvoiceDate between #" + dtpInvoiceDateFrom.Text + "# And #" + dtpInvoiceDateTo.Text + "# order by InvoiceDate desc", con);

使用如下参数

use parameters like below
cmd = new SqlCommand("SELECT (InvoiceNo) as [Invoice No],(InvoiceDate) as [Invoice Date],(Sales.CustomerID) as [Customer ID],(CustomerName) as [Customer Name],(GrandTotal) as [Grand Total],(TotalPayment) as [Total Payment],(PaymentDue) as [Payment Due] from Sales,Customer where Sales.CustomerID=Customer.CustomerID and InvoiceDate between @dtFrom And @dtTo order by InvoiceDate desc", con);
cmd.Parameters.AddWithValue("@dtFrom", fromDate);// convert your dtpInvoiceDateFrom.Text to DateTime and set here
cmd.Parameters.AddWithValue("@dtTo", toDate);// convert your dtpInvoiceDateTo.Text to DateTime and set here


将#替换为单引号,如[']和再试一次。



Replace # with single quotation like ['] and try again.

cmd = new SqlCommand("SELECT (InvoiceNo) as [Invoice No],(InvoiceDate) as [Invoice Date],(Sales.CustomerID) as [Customer ID],(CustomerName) as [Customer Name],(GrandTotal) as [Grand Total],(TotalPayment) as [Total Payment],(PaymentDue) as [Payment Due] from Sales,Customer where Sales.CustomerID=Customer.CustomerID and InvoiceDate between '" + dtpInvoiceDateFrom.Text + "' And '" + dtpInvoiceDateTo.Text + "' order by InvoiceDate desc", con);





如果你得到的无效日期时间错误比你需要将日期格式化为yyyy-mm-dd格式,然后重试。顺便说一句,解决方案1更优雅。



If you get invalid datetime error than you need to format your date into yyyy-mm-dd format and try again. By the way Solution 1 is more elegant.


尝试用单引号替换#,让我们知道是否有效
Try replacing # with single quotes and let us know if that works