Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Oracle SQL to change column type from number to varchar2 while it contains data

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 UDA1 from number to varchar2.

Proposed method:

  1. backup table
  2. set column to null
  3. change data type
  4. restore values

The following didn't work.

create table temp_uda1 AS (select * from UDA1); 

update UDA1 set TEST1 = null;
commit;

alter table UDA1 modify TEST1 varchar2(3);

insert into UDA1(TEST1)
  select cast(TEST1 as varchar2(3)) from temp_uda1;
commit;

There is something to do with indexes (to preserve the order), right?

like image 499
Din Avatar asked Sep 24 '13 09:09

Din


2 Answers

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

like image 72
a_horse_with_no_name Avatar answered Oct 11 '22 00:10

a_horse_with_no_name


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;
like image 31
mkb Avatar answered Oct 10 '22 22:10

mkb