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

前端 未结 5 649
遇见更好的自我
遇见更好的自我 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, <>);
    
    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.

提交回复
热议问题