I have a table (that contains data) in Oracle 11g and I need to use Oracle SQLPlus to do the following:
Target: change the type of column TEST1
in table
create table temp_uda1 (test1 integer);
insert into temp_uda1 values (1);
alter table temp_uda1 add (test1_new varchar2(3));
update temp_uda1
set test1_new = to_char(test1);
alter table temp_uda1 drop column test1 cascade constraints;
alter table temp_uda1 rename column test1_new to test1;
If there was an index on the column you need to re-create it.
Note that the update will fail if you have numbers in the old column that are greater than 999. If you do, you need to adjust the maximum value for the varchar
column
Look at Oracle's package DBMS_REDEFINE
. With some luck you can do it online without downtime - if needed. Otherwise you can:
VARCHAR2
columnupdate
to copy NUMBER
into VARCHAR2
NUMBER
columnVARCHAR2
columnHere you go, this solution did not impact the existing NOT NULL or Primary key constraints. Here i am going to change the type of Primary key from Number to VARCHAR2(3), Here are the Steps on example table employee.
create table employee_bkp as select * from employee
commit;
truncate table employee
ALTER TABLE employee MODIFY employee_id varchar2(30);
insert into employee (select * from employee_bkp)
commit;
Add new column as varchar2, copy data to this column, delete old column, rename new column as actual column name:
ALTER TABLE UDA1
ADD (TEST1_temp VARCHAR2(16));
update UDA1 set TEST1_temp = TEST1;
ALTER TABLE UDA1 DROP COLUMN TEST1;
ALTER TABLE UDA1
RENAME COLUMN TEST1_temp TO TEST1;