簡體   English   中英

如何使用數據更改列的數據類型

[英]How to change datatype of column with data

假設我有一個表call_log有一個名為duration的列。 讓我們進一步假設,當我把表格放在一起時,我犯了一個錯誤,將duration設為 varchar 列而不是數字。 現在我無法對該列進行正確排序。 我想重命名該列,所以我發出...

ALTER TABLE call_log MODIFY (duration NUMBER);

但我得到...

ORA-01439: column to be modified must be empty to change datatype.

我的表一直在用,有數據! 而且我不想丟失數據。 如何在不丟失數據的情況下修改列的數據類型?

創建一個具有正確數據類型的臨時列,將數據復制到新列,刪除舊列,重命名新列以匹配舊列的名稱。

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;

這個答案的想法來自Oracle 的論壇

以前的解決方案非常好,但是如果您不想更改 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;

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

注意2:此解決方案假設您的數據量不大。

保留列的原始順序的最佳解決方案:創建一個臨時列,將數據復制到其中,將原始列設置為空,修改其類型,將臨時列中的數據設置回它並刪除臨時列:

ALTER TABLE call_log ADD duration_temp NUMBER;
UPDATE call_log SET duration_temp = duration;
UPDATE call_log SET duration = NULL;
ALTER TABLE call_log MODIFY duration NUMBER;
UPDATE call_log SET duration = duration_temp;
ALTER TABLE call_log DROP (duration_temp);

或某些限制,我無法使用前兩種解決方案:

CREATE TABLE call_log_temp AS (SELECT * FROM call_log where rownum = 0);
ALTER TABLE call_log_temp MODIFY duration NUMBER;
INSERT INTO call_log_temp( id, duration, and_all_other_columns, ... )
  SELECT id, duration, and_all_other_columns, ...
  FROM call_log;  
DROP TABLE call_log;    
ALTER TABLE call_log_temp RENAME TO call_log;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM