trying to figure out how to get SQL to read a value as a date.
I have a db that has columns like this:
id created_at
1 2010-12-16
2 2010-12-16
3 2010-12-17
4 2010-12-21
5 2010-12-23
6 2011-01-04
I did not create the table using SQL; it was generated as text and imported to an SQL server. I’m not sure how to write my query so that it knows that created_at is a date, so I can use clauses like “WHERE created_at <‘2010-10-17’, etc, like I can do from a normal SQL db. Is Cast the route to go here? As in SELECT Cast(created_at as …something?) haven’t been able to find anything useful elsewhere.
if using SQL Server you can cast the column as a date as you’ve guessed:
However you’d need to do that each time you queried the table which is pretty inefficient. Better would be to redefine the table to make that column a date type by default. If you can post your table’s DDL statement (sql to create the table) up here I can write your conversion code for you. Alternatively, use the code below to alter the table after creation:
Cheers,
JB
Edit based on comments. If you’re unable to change the datatype and it’s an ntext column, first use substring to convert to an nvarchar, then use the cast function: