Sunday, July 19, 2009

How to change datatype of a column if the data in that column exists?

The above question many of you might have faced that how to change the datatype of the column if the data in the column already exists.

Here is the solution.
1. Suppose for example the below is the table
desc emp
id number
name varchar2(50)

Now you want to change the datatype of id to varchar2(20)

2. Add a dump column say xyz to the table emp
alter table emp
add xyz varchar2(20)

3. Copy the data from the id column to the xyz column
update emp
set xyz=id;
Crosscheck the data and commit the transaction.
commit;

4. Update all the rows of the id solution with NULL Values.
update emp
set id=NULL;
Crosscheck and commit the transaction.
commit;

5. Now the id column is having no data so change its datatype.
alter table emp
modify id varchar2(20);

6. Now copy the data back from xyz column to id column.
update emp
set id=xyz;
Crosscheck the data and commit the transaction.
commit;

7. Now drop the column xyz as its purpose is over.
alter table emp
drop column xyz;

Hope this helps.....

No comments: