FrenchJericho
asked on
SQL Server Error 8115 - CONVERT varchar to datetime
The following SELECT statement works fine:
SELECT * FROM MyTable WHERE ISDATE(MyStringField) = 1 AND CONVERT(datetime, MyStringField) < GETDATE()
However, the following UPDATE fails:
UPDATE MyTable SET StatusField = 'Overdue' WHERE ISDATE(MyStringField) = 1 AND CONVERT(datetime, MyStringField) < GETDATE()
The error message is:
Server: Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type datetime.
The statement has been terminated.
Is there a way to figure out which row is causing this problem and can anyone suggest how I can modify my statement to fix this error?
SELECT * FROM MyTable WHERE ISDATE(MyStringField) = 1 AND CONVERT(datetime, MyStringField) < GETDATE()
However, the following UPDATE fails:
UPDATE MyTable SET StatusField = 'Overdue' WHERE ISDATE(MyStringField) = 1 AND CONVERT(datetime, MyStringField) < GETDATE()
The error message is:
Server: Msg 8115, Level 16, State 2, Line 1
Arithmetic overflow error converting expression to data type datetime.
The statement has been terminated.
Is there a way to figure out which row is causing this problem and can anyone suggest how I can modify my statement to fix this error?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
You suggestion works like a charm! Thanks.
However, I was checking for ISDATE(MyStringField) = 1 in my original query so I don't understand why it didn't work. Anybody can help me understand?
However, I was checking for ISDATE(MyStringField) = 1 in my original query so I don't understand why it didn't work. Anybody can help me understand?
I don't understand why it didn't work since it's connected by an AND condition:
"WHERE ISDATE(MyStringField) = 1 AND CONVERT(datetime, MyStringField) < GETDATE()"
Once SQL determines that the ISDATE is false, it should not even evaluate the CONVERT -- they both can't be true ("... AND ...") if the first one is not true. Usually SQL optimizers are very good at recognizing these situations and exploiting them to do as little calcuation/retrieval as is absolutely necessary.
If the connector were "OR", it would have to evaluate both, and I could see the error occuring.
"WHERE ISDATE(MyStringField) = 1 AND CONVERT(datetime, MyStringField) < GETDATE()"
Once SQL determines that the ISDATE is false, it should not even evaluate the CONVERT -- they both can't be true ("... AND ...") if the first one is not true. Usually SQL optimizers are very good at recognizing these situations and exploiting them to do as little calcuation/retrieval as is absolutely necessary.
If the connector were "OR", it would have to evaluate both, and I could see the error occuring.
SELECT *
FROM MyTable
WHERE ISDATE(MyStringField) = 0
--AND MyStringField > ' ' --include this if desired to eliminate NULL and empty strings