Thursday, November 22, 2007

Changing column data type with data

Recently my friend came with a stragne requirement. He has data in one of the columns which is date value but the table is wrongly created as varchar2 column. He wants to change the datatype from varchar2 to date.

Here it goes

First created a table like this

create table a(id number, dt1 varchar2(20));

Inserted some values into the table using following queries

insert into a values (4,'04/jul/2007')
insert into a values (1,'01/jul/2007')
insert into a values (2,'02/jul/2007')


Now create another column in the same table like this
alter table a add dt2 date


Now update the newly created column with the existing value using the query

update a set dt2=to_date(dt1)


Drop the varchar2 column from the table using
alter table a drop column dt1

Rename the newly created column
alter table a rename column dt2 to dt1

No comments: