错误:从字符串转换日期和/或时间时转换失败

本文关键字:转换 时间 失败 日期 字符串 错误 | 更新日期: 2023-09-27 18:17:17

如何解决此错误?

从字符串

转换日期和/或时间时,转换失败

My SQL code:

SELECT 
   RTRIM(invoiceNo) as [Order No.],
   RTRIM(InvoiceDate) as [Order Date],
   RTRIM(SubTotal) as [SubTotal],
   RTRIM(VATPer) as [Vat+ST %],
   RTRIM(VATAmount) as [VAT+ST Amount],
   RTRIM(DiscountPer) as [Discount %],
   RTRIM(DiscountAmount) as [Discount Amount],
   RTRIM(GrandTotal) as [Grand Total],
   RTRIM(TotalPayment) as [Total Payment],
   RTRIM(PaymentDue) as [Payment Due] 
FROM  
   Invoice_Info 
WHERE 
   InvoiceDate BETWEEN @d1 AND @d2 
ORDER BY  
   InvoiceDate desc

我使用c#中的SqlCommand来调用它,添加这些参数:

cmd.Parameters.Add("@d1", SqlDbType.DateTime, 30, "InvoiceDate").Value = dtpInvoiceDateFrom.Value.Date;
cmd.Parameters.Add("@d2", SqlDbType.DateTime, 30, "InvoiceDate").Value = dtpInvoiceDateTo.Value.Date;

错误:从字符串转换日期和/或时间时转换失败

我认为你必须去掉"。Date",因为DateTimePicker.Value.Date只返回字段的日期部分。

也可以将参数修改如下:

cmd.Parameters.Add("@d1", SqlDbType.DateTime).Value = dtpInvoiceDateFrom.Value;
cmd.Parameters.Add("@d2", SqlDbType.DateTime).Value = dtpInvoiceDateTo.Value;