修改oracle数据库表字段类型,处理ORA-01439错误
2015-05-24 11:41
393 查看
对已经有数据的表修改字段类型时,Oracle提示:ORA-01439: 要更改数据类型, 则要修改的列必须为空。
可以创建新表,灌入原表数据后再改名,或者创建临时字段,替换数据后再删除。
测试环境:
drop table foo;
create table foo (col_name varchar2(5));
insert into foo values('1');
insert into foo values('12');
insert into foo values('33445');
commit;
create index idx1 on foo (col_name);
select * from foo;
desc foo
解决方法
1. 创建新表
根据当前表结构创建新表,修改新表字段,将原数据灌进来,删除旧表,将新表rename为旧表名
create table new as select * from foo where 1=2;
alter table new modify (col_name number(5));
insert into new select * from foo;
drop table foo;
rename new to foo;
如果原表有索引,触发器、外键等需要新建。
2. 使用CTAS来转换
oracle 的使用查询创建表的功能创建一个新表包含原来的数据,命令如下:
create table new
as
select [其他的列],
to_number(Char_Col) col_name
from foo;
然后drop 原表,新表更名为原表:
drop table foo;
rename new to foo;
与方法1一样要注意新建相关对象。
3. 创建临时字段替换《推荐此种方式》
新建一个临时字段,把要修改的字段的内容备份到临时字段后清空原字段,然后再修改类型,之后再把临时字段的内容复制到修改后的字段,最后删除临时字段 (注意字段间格式的转换 to_number(XX)、TO_CHAR(XX)等等)
alter table foo add(col_name2 number(5));
update foo set col_name2= to_number(col_name);
update foo set col_name = null; --此处要小心啊,原数据全没了,一定要保证上一步正确执行
alter table foo modify (col_name number(5));
update foo set col_name = col_name2;
alter table foo drop column col_name2;
可以创建新表,灌入原表数据后再改名,或者创建临时字段,替换数据后再删除。
测试环境:
drop table foo;
create table foo (col_name varchar2(5));
insert into foo values('1');
insert into foo values('12');
insert into foo values('33445');
commit;
create index idx1 on foo (col_name);
select * from foo;
desc foo
解决方法
1. 创建新表
根据当前表结构创建新表,修改新表字段,将原数据灌进来,删除旧表,将新表rename为旧表名
create table new as select * from foo where 1=2;
alter table new modify (col_name number(5));
insert into new select * from foo;
drop table foo;
rename new to foo;
如果原表有索引,触发器、外键等需要新建。
2. 使用CTAS来转换
oracle 的使用查询创建表的功能创建一个新表包含原来的数据,命令如下:
create table new
as
select [其他的列],
to_number(Char_Col) col_name
from foo;
然后drop 原表,新表更名为原表:
drop table foo;
rename new to foo;
与方法1一样要注意新建相关对象。
3. 创建临时字段替换《推荐此种方式》
新建一个临时字段,把要修改的字段的内容备份到临时字段后清空原字段,然后再修改类型,之后再把临时字段的内容复制到修改后的字段,最后删除临时字段 (注意字段间格式的转换 to_number(XX)、TO_CHAR(XX)等等)
alter table foo add(col_name2 number(5));
update foo set col_name2= to_number(col_name);
update foo set col_name = null; --此处要小心啊,原数据全没了,一定要保证上一步正确执行
alter table foo modify (col_name number(5));
update foo set col_name = col_name2;
alter table foo drop column col_name2;
相关文章推荐
- 修改oracle数据库字段类型,处理ORA-01439错误
- 修改oracle数据库字段类型,处理ORA-01439错误
- 修改oracle数据库字段类型,处理ORA-01439错误
- oracle修改字段类型时报"要更改的列必须为空"处理方法
- Oracle数据库修改字段类型
- racle修改字段类型时报"要更改的列必须为空"处理方法
- oracle修改字段类型时报"要更改的列必须为空"处理方法
- 修改SQL数据库中表字段类型时,报“一个或多个对象访问此列”错误的解决方法
- Oracle数据库Date类型字段读写经验、查看Oracle字符集及修改字符集
- oracle数据库对date字段类型存在空值进行排序的处理方法
- 修改SQL数据库中表字段类型时,报“一个或多个对象访问此列”错误的解决方法
- oracle数据库有数据如何修改字段类型
- 关于修改表字段数据类型的问题(ORA-22859: 无效的列修改 )
- Oracle修改字段类型时报"要更改的列必须为空"处理方法
- oracle修改字段类型时报"要更改的列必须为空"处理方法
- SQL Server2008修改数据表字段类型保存提示错误
- oracle处理已有数据的字段(主键)类型修改方法
- ORA-01439:要更改数据类型,则要修改的列必须为空
- 修改SQL数据库中表字段类型时,报“一个或多个对象访问此列”错误的解决方法
- 数据库技巧-批量修改ORACLE数据库的字段类型