Click here to Skip to main content
16,016,180 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have a column in my table that is varchar. I use it to store dates in the format
e.g. 01/12/2013 What I would like to do is convert the column to DataType datetime or date. I'm new to SQL so having hard time with it. All the dates stored are different.
Posted

try this.. :)

SQL
select convert(datetime,columnName)  as [DateTime]
select convert(date,columnName)  as [Date]

--or
select cast(columnName as datetime)  as [DateTime]
select cast(columnName as date)  as [Date]
 
Share this answer
 
Firstly, well done for realising that you need to use the correct column type for dates. It avoids formatting problems and takes up less space.

As you already have your table you have a few options when it comes to converting that column.

1. You could drop the table entirely, recreate it and re-populate it

2. You could add an extra column of the correct type then use the technique from solution 1 to populate the new column. E.g.
SQL
UPDATE tablename SET newColumn = CONVERT(date, oldColumn,103)

(You might want to delete the old column afterwards). You can do this with ALTER TABLE or via Management Studio

3. You could create a new table from the contents of the old one e.g.
SQL
SELECT column1, column2, column3, CONVERT(date, oldColumn,103), .. etc
INTO NewTable FROM OldTable

(NB you must list the other columns) and then drop the old table
If it was me I would probably go with option 1 unless you really have lots of data you can't easily reproduce

[EDIT - added ,103 as the format to use on CONVERT]
 
Share this answer
 
v2
Comments
johnjsm 29-May-14 9:26am    
Sorry about putting question in wrong location

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900