简体   繁体   中英

Modify a column to remove or change default value in oracle 11g

I have a Table T1 in oracle 11g

T1
(
C1 number, 
C2 date default sysdate,
C3 varchar2(20)
);

I want to modify my c2 column to number(9) , however when i run below alter table im getting error.

alter table T1 modify C2 number(9);    -- getting error .
alter table T1 modify C2 varcha2(10);  -- run successfully .

can anybody tell the reason for this and how i can modify it without droping and recreate the table ?

Column C2 current definition:

C2 date default sysdate

When you're altering this column to VARCHAR2(10) there is no problem, because Oracle performs an implicit conversion of the values from DATE to VARCHAR2 using current NLS_SETTINGS (date string representation pattern for example)

When you're altering the column to NUMBER(9) Oracle cannot apply an implicit conversion (there is no such rule in its conversion matrix). That's why you're getting an error.

One way to alter is to make the column null:

update t1 set c2 = null;
alter table T1 modify C2 number(9);

Be aware that ALTER is DDL, which means it performs an implicit COMMIT right before and right after the operation.

If you need to save the data in C2 and convert it to NUMBER you can add a new column, make the conversion, drop the old column, and rename the new column:

alter table T1 add C2_new number(9);
update t1 set c2_new = <your conversion of C2>;
alter table T1 drop column C2;
alter table T1 rename column C2_new to C2;

(don't forget about DDL which you cannot ROLLBACK)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM