Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1774396
  • 博文数量: 323
  • 博客积分: 5970
  • 博客等级: 大校
  • 技术积分: 2764
  • 用 户 组: 普通用户
  • 注册时间: 2011-04-03 23:13
文章分类

全部博文(323)

文章存档

2018年(2)

2017年(11)

2016年(10)

2015年(27)

2014年(2)

2013年(30)

2012年(197)

2011年(44)

分类: Oracle

2012-05-12 11:29:21

 (2011-08-26 12:19)一键转载



对已经有数据的表修改字段类型时,Oracle提示:ORA-01439: 要更改数据类型, 则要修改的列必须为空。
可以创建新表,灌入原表数据后再改名,或者创建临时字段,替换数据后再删除。
 
测试环境:
  1. drop table foo;
  2. create table foo (col_name varchar2(5));
  3. insert into foo values('1');
  4. insert into foo values('12');
  5. insert into foo values('33445');
  6. commit;
  7. create index idx1 on foo (col_name);
  8. select * from foo;
  9. desc foo
解决方法
 
1. 创建新表
根据当前表结构创建新表,修改新表字段,将原数据灌进来,删除旧表,将新表rename为旧表名
  1. --此处1=2表示只导入格式,因为表达式为假,不会导入数据
  2. create table new as select * from foo where 1=2;                                            
  3. alter table new modify (col_name number(5));
  4. insert into new select * from foo;
  5. drop table foo;
  6. rename new to foo;
如果原表有索引,触发器、外键等需要新建。
 
2.  使用CTAS来转换
oracle 的使用查询创建表的功能创建一个新表包含原来的数据,命令如下: 
  1. create table new
  2. as 
  3. select [其他的列], 
  4.  to_number(Char_Col) col_name
  5. from foo;
然后drop 原表,新表更名为原表: 
  1. drop table foo; 
  2. rename new to foo;
与方法1一样要注意新建相关对象。
 
3. 创建临时字段替换
新建一个临时字段,把要修改的字段的内容备份到临时字段后清空原字段,然后再修改类型,之后再把临时字段的内容复制到修改后的字段,最后删除临时字段
  1. alter table foo add(tmp_col number(5));
  2. update foo set tmp_col = to_number(col_name);
  3. update foo set col_name = null; --此处要小心啊,原数据全没了,一定要保证上一步正确执行

  4. alter table foo modify (col_name number(5));
  5. update foo set col_name = tmp_col;
  6. alter table foo drop column tmp_col;
阅读(820) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~