当前位置:   article > 正文

添加唯一性约束 延迟生效_表存在数据时 alter table add constraint using index nova

表存在数据时 alter table add constraint using index novalidate

已存在数据的表,发现某字段缺失唯一性约束,现在要添加唯一性约束,操作如下:

-- 添加唯一性约束,延迟生效
alter table t add constraint uq_t_col1 unique (col1) using index
deferrable enable novalidate;
-- alter table t add constraint pk_t primary key (col1) 
-- deferrable enable novalidate;

-- 查看重复数据
select col1,count(*) from t
 group by col1 having count(*)>1;

-- 数据滤重
delete from t where rowid not in (
  select min(rowid) from t group by col1);

-- 修改约束状态,恢复正常
alter table t enable validate constraint uq_t_col1;
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
使用参数deferrable指定延迟生效:
deferrable disable novalidate
--不生效,不校验已有数据
deferrable disable validate
--不生效,校验已有数据
deferrable enable novalidate
--生效,不校验已有数据
deferrable enable validate
--生效,校验已有数据,也就是默认状态
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/很楠不爱3/article/detail/653109
推荐阅读