Link to home
Start Free TrialLog in
Avatar of Edward Diaz
Edward DiazFlag for United States of America

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
Avatar of Anthony Perkins
Anthony Perkins
Flag of United States of America image

>>Is it possible to simply cast the text dates to temporarily make them dates for query purposes?<<
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)
ASKER CERTIFIED SOLUTION
Avatar of Brendt Hess
Brendt Hess
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
Oops, that should have been:
CONVERT(datetime, CAST(YourDateColumn as varchar(10)), 101)
Avatar of Edward Diaz

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

If there is any chance that YourDateColumn is not valid than you will have to do something like this:

CASE
      WHEN ISDATE(CAST(@YourDateColumn as varchar(10))) = 1 THEN CONVERT(datetime, CAST(@YourDateColumn as varchar(10)), 101)
      ELSE Null
END
SOLUTION
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
Thanks Bhess and acperkins! Both solutions worked, so I split the points evenly.

Kittrick