APD Toronto
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
You will see that I am trying two formats, both unsuccessfull
When I do a simple SELECT ..... ,CAST(paymentDate AS DATE) AS dt I get YYYY-MM-DD
Thank you,
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.
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)
When I do a simple SELECT ..... ,CAST(paymentDate AS DATE) AS dt I get YYYY-MM-DD
Thank you,
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
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
ASKER
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Don't use CAST() but TRY_CAST() in the WHERE clause. It will avoid conversion problem.
Try convert with the correct style for the strings you have:
https://www.w3schools.com/sql/func_sqlserver_convert.asp