如何使用数据更改列的数据类型

mas*_*son 5 sql oracle

假设我有一个call_log名为列的表duration.让我们进一步假装当我把桌子放在一起时,我犯了duration一个错误,就是做一个varchar列而不是一个数字.现在我无法正确排序该列.我想重命名列,所以我发出...

ALTER TABLE call_log MODIFY (duration NUMBER);
Run Code Online (Sandbox Code Playgroud)

但我明白了......

ORA-01439: column to be modified must be empty to change datatype.
Run Code Online (Sandbox Code Playgroud)

我的桌子一直在使用,有数据!而且我不想丢失数据.如何在不丢失数据的情况下修改列的数据类型?

mas*_*son 14

使用正确的数据类型创建临时列,将数据复制到新列,删除旧列,重命名新列以匹配旧列的命名.

ALTER TABLE call_log ADD (duration_temp NUMBER);
UPDATE call_log SET duration_temp = duration;
ALTER TABLE call_log DROP COLUMN duration;
ALTER TABLE call_log RENAME COLUMN duration_temp TO duration;
Run Code Online (Sandbox Code Playgroud)

这个答案的想法来自Oracle的论坛.


Eng*_*r T 6

以前的解决方案非常好,但是如果您不想更改 call_log 表结构中的列顺序,则执行以下步骤:

create table temp_call_log  as select * from call_log; /* temp backup table for call_log */
UPDATE call_log SET duration = null;
/*check,... be sure.... then commit*/
commit;
ALTER TABLE call_log MODIFY duration NUMBER;
UPDATE call_log c SET c.duration = (select t.duration from temp_call_log t where t.primarykey_comumn = c.primarykey_column);
/*check,... be sure.... then commit*/
commit;
drop table temp_call_log;
Run Code Online (Sandbox Code Playgroud)

注意1:使用表call_log 中的主键更改primarykey_comumn。

注意2:此解决方案假设您的数据量不大。