Link to home
Start Free TrialLog in
Avatar of APD Toronto
APD TorontoFlag for Canada

asked on

SQL Cast as Date

Hi Experts,

I am working with an old MS SQL database where the date is stored as Varchar, but I keep getting the following error

Msg 241, Level 16, State 1, Line 1
Conversion failed when converting date and/or time from character string.

Open in new window


You will see that I am trying two formats, both unsuccessfull
SELECT SUM(family) AS totFam, SUM(adults) AS totAdult, SUM(Seniors) AS totSen, SUM(students) AS totStud, 
SUM(children) AS totChild, SUM(infants) AS totInf 
FROM Invoices 

WHERE CAST( CASE WHEN responseCode IS NULL OR ISNUMERIC(ResponseCode) = 0 THEN '99' else responsecode end AS INT) < 50 
AND (Company = 'CSST' OR Company = 'COMBO') 

/*AND CAST(paymentDate AS DATE) >= CAST('12/5/2019' AS DATE) AND CAST(paymentDate AS DATE) <= CAST('3/24/2020' AS DATE)*/
AND CAST(paymentDate AS DATE) >= CAST('2019-12-05' AS DATE) AND CAST(paymentDate AS DATE) <= CAST('2020-03-24' AS DATE)

Open in new window


When I do a simple SELECT ..... ,CAST(paymentDate AS DATE) AS dt I get YYYY-MM-DD

Thank you,
Avatar of slightwv (䄆 Netminder)
slightwv (䄆 Netminder)

Might be the data in the column isn't convertible to a date.

Try convert with the correct style for the strings you have:
https://www.w3schools.com/sql/func_sqlserver_convert.asp
Avatar of APD Toronto

ASKER

BY the way, some data is NULL
>>BY the way, some data is NULL                                  

Doesn't matter.  Even if it is an empty string and not null, cast will still provide something:
https://dbfiddle.uk/?rdbms=sqlserver_2012&fiddle=a229f3e54c96b79e85096a10970987e7
So why does my first query throw an error, but my second does the conversion as expected? Can it be my AND condition?
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Don't use CAST() but TRY_CAST() in the WHERE clause. It will avoid conversion problem.