Edward Diaz
asked on
Converting DB date in text format to date
I have a database in which the date fields were converted to text ( I inheirited the database). Now I would like to query the database, but the dates are stuck in text format. I need to convert them so I can compare date ranges in a query.
I'm using SQL Query Analyzer to test the SQL query string, and I get this message:
Server: Msg 306, Level 16, State 1, Line 3
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
Is it possible to simply cast the text dates to temporarily make them dates for query purposes?
Please provite a simple SQL query for this.
Thanks!
Kittrick
I'm using SQL Query Analyzer to test the SQL query string, and I get this message:
Server: Msg 306, Level 16, State 1, Line 3
The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator.
Is it possible to simply cast the text dates to temporarily make them dates for query purposes?
Please provite a simple SQL query for this.
Thanks!
Kittrick
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Oops, that should have been:
CONVERT(datetime, CAST(YourDateColumn as varchar(10)), 101)
CONVERT(datetime, CAST(YourDateColumn as varchar(10)), 101)
ASKER
Thanks for your reply acperkins. How would I use it in the SQL query?
Here's my SQL statement:
SELECT ID, Start_date FROM database WHERE start_date>=1/1/2006
Here's my SQL statement:
SELECT ID, Start_date FROM database WHERE start_date>=1/1/2006
If there is any chance that YourDateColumn is not valid than you will have to do something like this:
CASE
WHEN ISDATE(CAST(@YourDateColum n as varchar(10))) = 1 THEN CONVERT(datetime, CAST(@YourDateColumn as varchar(10)), 101)
ELSE Null
END
CASE
WHEN ISDATE(CAST(@YourDateColum
ELSE Null
END
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thanks Bhess and acperkins! Both solutions worked, so I split the points evenly.
Kittrick
Kittrick
Yes, but only if the format is well defined. For example, assuming mm/dd/yyyy than the following should work:
CONVERT(datetime, CAST(YourDateColumn as varchar(10), 101)