SQL USING CAST in a query inside a stored Procedure

castcursorsstored-procedures

I was trying to use a query inside an Stored procedure which has a cast funtion. But when executing the SP I'm getting an error

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

SELECT * 
  FROM TEMPTABLE 
 WHERE Status = 'A' 
   AND technician = 5 
   and schid not in (1047) 
   and CAST(approxstartdate as datetime)  > = 
       ( select CAST(approxstartdate as datetime)  
           from trscheduler where Status = 'A' 
            AND technician = 5 
            and schid = 1059
       ) 
 order by  CAST(approxstartdate as datetime) 

This query is used in a cursor.

Kindly let me know an alternative for this.

Best Answer

You have data in approxstartdate column that cannot be converted to datetime, it’s bad data, chances are if you saw what that data is you wouldn’t know how to convert it to a datetime either.

If you are using SQL Server, take a look at try_convert which returns null if the value cannot be converted. You can use this function to find the values in your table that cannot be converted and then fix them or remove them.