栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在我的表中创建SQL约束

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在我的表中创建SQL约束

通常,在您基于表格顶部构建的API中强制执行此类约束以操纵百分比会更有意义。当然,假设每次

product_group_id
最多只能一次会话。

如果确实要实施这种限制,则可以创建一个物化视图,该视图在提交时刷新,并在该物化视图上创建约束。就像是

SQL> create table table_name(  2    id number primary key,  3    product_group_id number,  4    percentage number  5  );Table created.SQL> create materialized view log on table_name;Materialized view log created.SQL> edWrote file afiedt.buf  1  create materialized view mv_table_name  2    refresh on commit  3  as  4  select product_group_id, sum(percentage) total_percentage  5    from table_name  6*  group by product_group_idSQL> /Materialized view created.SQL> alter table mv_table_name  2    add( constraint sum_of_1 check( total_percentage = 1 ));Table altered.

这样您就可以插入总和为1的行

SQL> insert into table_name values( 1, 1, 0.5 );1 row created.SQL> insert into table_name values( 2, 1, 0.5 );1 row created.SQL> commit;Commit complete.

并尝试提交导致总和不是1的更改时将抛出错误

SQL> insert into table_name values( 3, 1, 0.1 );1 row created.SQL> commit;commit*ERROR at line 1:ORA-12008: error in materialized view refresh pathORA-02290: check constraint (SCOTT.SUM_OF_1) violated

请注意,这确实是在提交时检查的,这是您真正需要的,因为当您要插入多行时,在事务期间您将需要违反约束。

并且,正如已经指出的那样,如果存在舍入误差的可能性,则您可能希望

CHECK
约束条件允许总和为1
+/-一些小ε(即,介于0.999999和1.000001之间)



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/380630.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号