how to solve Passing DateTime value to paramaterized query Error

221 views Asked by At

here is my query string

SELECT
Payment
,Balance
,PatientNo
FROM
[GP_DB].[dbo].[GP]
where GP.GPDate= (SELECT CONVERT(VARCHAR(24),@GPDate,103))

GPDate is a Date type column, not DateTime

and i pass parameter like this

cmd_select_treatment.Parameters.AddWithValue(
            "@GPDate"
            ,Convert.ToDateTime(dateTimePicker1.Value));

but the following error occur

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

3

There are 3 answers

0
donata On BEST ANSWER

@var is DateTime select cast(convert (varchar(8),@var,112) as Date)

0
smn_onrocks On

I Think you need to add picture clause in your date conversion like the example

to_date('18/01/2014 10:15:20','dd/mm/yyyy hh24:mi:ss');

this should solve your problem

0
ta.speot.is On

GPDate is a Date type column

If it's a DATE column and your Convert.ToDateTime call returns a DateTime object then don't bother yourself with the CAST.

WHERE GP.GPDate = @GPDate

If dateTimePicker1 might contain a time component and you don't care for that then simply discard it before using its value:

Convert.ToDateTime(dateTimePicker1.Value).Date