I’m running into an issue casting a VARCHAR in one table into a DATETIME and then using it in a comparison. The format (‘2010-09-02 10:38:31.000’) seems to be correct on all of the records, and I can select the data without any problems. However, if I try to use the new datetime in the WHERE clause, I get the error: Conversion failed when converting date and/or time from character string.
So just to be clear, this works:
SELECT Field1, Field2, CAST(Field3 AS DATETIME) AS DateTaken FROM MyTable;
That returns all of the data as expected, and there are no null dates. The following fails with the previously mentioned error.
SELECT Field1, Field2 FROM MyTable WHERE CAST(Field3 AS DATETIME) > @startDate;
I tried using a view to retrieve the data, but it had the same error. Next I tried creating a temporary table for the data like so…
SELECT Field1, Field2, CAST(Field3 AS DATETIME) AS Field3 INTO _MyTable;
SELECT Field1, Field2 FROM _MyTable WHERE Field3 > @startDate;
Which works successfully.
All of my searching just leads to incorrectly formatted dates and / or regional settings causing havok which does not appear to be the cause in my case. I’d rather not create a table every time I need to use a DATETIME cast, so what am I doing wrong here? Help is much appreciated!
edit # 3…………..
edit # 2…………..
I did a test on my db…
Results:
changing the startdate param to 10/1/2010
Results:
1st response……………..
Did you try Convert?