当前位置:数据库 > Oracle >>

记录一次删除Oracle表字段的非空约束

记录一次删除Oracle表字段的非空约束
 
一个表表结构指定了某个字段(如cno)not null,同时加了check not null约束。
现在需要将not null约束去掉,要让cno字段可以插入空值。
于是执行了下面的语句:
Sql代码  
1.alter table tableName drop constraints not_null_cons_cno;  
2.alter table tableName modify cno null;  

 

 
语句执行完毕,还是不能插入空值。
报如下错误:
ORA-01451: column to be modified to NULL cannot be modified to NULL 
查询了Oracle的文档,描述如下:
Cause: the column may already allow NULL values, the NOT NULL constraint is part of a primary key or check constraint.
Action: if a primary key or check constraint is enforcing the NOT NULL constraint, then drop that constraint.
 
然后我发现这个字段与其他的字段组成了一个唯一性的组合索引。
于是,我修改这个索引,从中删掉cno字段。
1.删除主键;
Sql代码  
alter table tableName drop constraints pk_tableName;  

2.删除唯一索引;
Sql代码  
drop index un_idx_table_name;  

3.创建主键(不包括cno字段);
Sql代码  
alter table tableName  
add constraint PK_tableName primary key (DNO, TNO, YEAR, PNO);  

 

 
4.创建唯一索引(不包括cno字段)。
Sql代码  
create unique index ix_tableName on tableName (DNO, TNO, YEAR, PNO);   

 

第3步报错了:
ORA-02437: cannot validate (TBOSDATA.PK_VOU_NUM) - primary key violated
这个错误是说主键或唯一键有重复记录。(我的唯一性约束作用在dno,tno,cno,year,pno几个字段。
查找重复的记录:
Sql代码  
select *  
 from test vnt  
where (vnt.dno, vnt.tno, vnt.year, vnt.pno) in  
            (select t.dno, t.tno, t.year, t.pno  
                 from test t  
                group by t.dno, t.tno, t.year, t.pno  
             having count(*) > 1)  
order by dno, tno, year, pno;  

 

 
删除重复记录或修改重复记录,然后重新执行上面的3,4就OK了。
 
Oracle
MySQL
Access
SQLServer
DB2
Excel
SQLite
SYBASE
Postgres
如果你遇到数据库难题:
请访问www.zzzyk.com 试试
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,