How to modify data type in Oracle with existing rows in table

前端 未结 5 640
遇见更好的自我
遇见更好的自我 2020-12-21 07:54

How can I change DATA TYPE of a column from number to varchar2 without deleting the table data?

相关标签:
5条回答
  • 2020-12-21 08:38

    You can't.

    You can, however, create a new column with the new data type, migrate the data, drop the old column, and rename the new column. Something like

    ALTER TABLE table_name
      ADD( new_column_name varchar2(10) );
    
    UPDATE table_name
       SET new_column_name = to_char(old_column_name, <<some format>>);
    
    ALTER TABLE table_name
     DROP COLUMN old_column_name;
    
    ALTER TABLE table_name
     RENAME COLUMN new_column_name TO old_coulumn_name;
    

    If you have code that depends on the position of the column in the table (which you really shouldn't have), you could rename the table and create a view on the table with the original name of the table that exposes the columns in the order your code expects until you can fix that buggy code.

    0 讨论(0)
  • 2020-12-21 08:41
    alter table table_name modify (column_name VARCHAR2(255));
    
    0 讨论(0)
  • 2020-12-21 08:42

    Since we can't change data type of a column with values, the approach that I was followed as below,

    Say the column name you want to change type is 'A' and this can be achieved with SQL developer.

    First sort table data by other column (ex: datetime). Next copy the values of column 'A' and paste to excel file. Delete values of the column 'A' an commit. Change the data type and commit. Again sort table data by previously used column (ex: datetime). Then paste copied data from excel and commit.

    0 讨论(0)
  • 2020-12-21 08:55

    The most efficient way is probably to do a CREATE TABLE ... AS SELECT
    (CTAS)

    0 讨论(0)
  • 2020-12-21 08:59

    You have to first deal with the existing rows before you modify the column DATA TYPE.

    You could do the following steps:

    1. Add the new column with a new name.
    2. Update the new column from old column.
    3. Drop the old column.
    4. Rename the new column with the old column name.

    For example,

    alter table t add (col_new varchar2(50));
    
    update t set col_new = to_char(col_old);
    
    alter table t drop column col_old cascade constraints;
    
    alter table t rename column col_new to col_old;
    

    Make sure you re-create any required indexes which you had.

    You could also try the CTAS approach, i.e. create table as select. But, the above is safe and preferrable.

    0 讨论(0)
提交回复
热议问题