問題描述:
項目使用了 oracle 數據庫,在一張設置了主鍵的表上,主鍵數據竟然還能插入重複的數據。主鍵的設置包含了唯一鍵,那麼到底是怎麼出現這樣的情況呢?
原因分析:
數據吧的主鍵雖然設置了,但是沒有啓動,這才導致可以插入重複主鍵數據。
解決方案:
- 查詢出沒有啓用主鍵的表
select a.constraint_name,b.column_name,a.table_name,a.status
from user_constraints a,user_cons_columns b
where a.constraint_type = 'P' and a.status='DISABLED' and b.column_name='seq';
- 查詢需要開啓主鍵的表是否有主鍵重複的數據,有的話需要刪除重複的數據
select a.* from 表名 a inner join 表名 b on a.seq=b.seq and a.rowid!=b.rowid
或者
select * from (select count(*) num,seq from 表名 group by seq )where num>1
- 啓用表主鍵
alter table 表名 enable primary key;
- 停用SYS_CONFIG 表主鍵
alter table 表名 disable primary key;
- 批量啓用主鍵
select 'alter table '||table_name|| ' enable primary key;' from
(select a.constraint_name,b.column_name,a.table_name,a.status
from user_constraints a,user_cons_columns b
where a.constraint_type = 'P' and a.status='DISABLED' and b.column_name='seq');