简体   繁体   中英

Error: Conversion failed when converting date and/or time from character string

How can I solve this error?

Conversion failed when converting date and/or time from character string

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

And I call this using a SqlCommand from C#, adding these parameters:

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

I think that you must remove the ".Date" from the values, because DateTimePicker.Value.Date is returning only the date part of the field.

Also you can change the parameters to the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM