Click here to Skip to main content
15,888,162 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

First thank you code project members!!

I am facing a problem in SQL SERVER. I wrote a dynamic query with dated where clause

as it is dynamic query it giving me error

Conversion failed when converting datetime from character string.

SQL
set @SQLQry ='Insert into #tmpSpeed(Speed) SELECT Speed FROM '
    +@tablenameSt+' WHERE SIMID ='+ @TrackerID +'
    AND dated between CONVERT(datetime,'''+@StartDateTime+ ''', 120)  and  CONVERT(datetime,'''+@EndDateTime+ ''', 120)'



Please tell how can it solved.

:(
Posted

When you specify the "style" as 120, you specify that SQL should treat the input string as canonical: i.e. yyyy-mm-dd hh:mi:ss(24h) If your data is not exactly that, then you will get an error.

MSDN[^]
 
Share this answer
 
Hi,

Check it your input.
May be you can pass the datetime in 'dd/MM/yyyy' format.

In Sql server,its consider the datetime in 'MM/dd/yyyy' format.
 
Share this answer
 
Comments
OriginalGriff 25-Mar-11 5:31am    
Unfortunately, that turns out not to be the case: SQL standard datetime format is "yyyy-mm-dd hh:mi:ss", and since he specifies style 120, that is what is expected.
T.Saravanann 25-Mar-11 5:48am    
of course..But his case there is no need to use style 120.Just he change the query into ...
set @SQLQry ='Insert into #tmpSpeed(Speed) SELECT Speed FROM '
+@tablenameSt+' WHERE SIMID ='+ @TrackerID +'
AND dated between CONVERT(datetime,'''+MM/dd/yyyy+''') and CONVERT(datetime,'''+MM/dd/yyyy+''')' ..This query also working fine.
Complete error detail with sample example here: http://www.sql-server-performance.com/faq/conversion_failed_datatime_character_p1.aspx[^]

Generally, SQL Server expects dates in the format mm/dd/yyyy, so you will need to convert your date into this format before submitting.

Try something like:
Dim myDatevalue as new SqlParameter("@StartDateTime", Format("myDatevalue","mm/dd/yyyy"))
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900