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

后端 未结 4 1126
广开言路
广开言路 2020-12-31 22:27

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

相关标签:
4条回答
  • 2020-12-31 22:51
    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

    0 讨论(0)
  • 2020-12-31 23:02

    Look at Oracle's package DBMS_REDEFINE. With some luck you can do it online without downtime - if needed. Otherwise you can:

    • Add new VARCHAR2 column
    • Use update to copy NUMBER into VARCHAR2
    • Drop NUMBER column
    • Rename VARCHAR2 column
    0 讨论(0)
  • 2020-12-31 23:05

    Here 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.

    1. Take backup of table and Index, Constraints created table employee_bkp create table employee_bkp as select * from employee commit;
    2. Truncate the table to empty it truncate table employee
    3. Alter the table to change the type ALTER TABLE employee MODIFY employee_id varchar2(30);
    4. Copy the data back from backup table insert into employee (select * from employee_bkp) commit;
    5. Verify
    0 讨论(0)
  • 2020-12-31 23:09

    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;
    
    0 讨论(0)
提交回复
热议问题