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

时间:2014-08-10 18:57:17

标签: c# sql-server-2008

如何解决此错误?

  

从字符串

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

我的SQL代码:

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;

1 个答案:

答案 0 :(得分:0)

我认为你必须从值中删除“.Date”,因为DateTimePicker.Value.Date只返回字段的日期部分。

您还可以将参数更改为以下内容:

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