Oracle检查完整性约束 [英] Oracle Check Integrity Constraint

查看:306
本文介绍了Oracle检查完整性约束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在Oracle中创建一个受几个完整性约束控制的表。该表由一个假设的学生数据库组成。数据库的规则之一是,对于被分类为初级学生的学生,他们必须完成55和84学分(含)之间。

I am trying to make a table in Oracle which is governed by several integrity constraints. The table consists of a hypothetical student database. One of the rules of the database is that for a student to be classified as a junior, they must have completed between 55 and 84 credit hours (inclusive).

我需要创建一个完整性约束来强制执行此规则,但不完全确定如何去做。我有一个感觉,CHECK约束将是有用的在这种情况下。

I need to create an integrity constraint to enforce this rule but am not entirely sure how to go about doing it. I have a feeling that a CHECK constraint would be useful in this situation.

到目前为止,我有...

So far I have...

CONSTRAINT IC4 CHECK (hours >=55 AND hours <= 84), 

此代码有效,不确定学生记录是否为初级学生。

This code is valid, however it does not determine if the student record is a junior.

我的表的设置是...

The set up of my table is...

    CREATE TABLE  Students ( id                INTEGER, 
                             name              CHAR(10)    NOT NULL,  
                             classification    CHAR(10)    NOT NULL, 
                             hours             INTEGER, 
                             gpa               NUMBER(3,2) NOT NULL, 
                             mentor            INTEGER); 

因此,如果我们尝试插入...

So if we try to insert...

INSERT INTO Students VALUES (50, 'Kim', 'junior', 34, 3.5, 40);  

...将违反完整性约束,因为记录试图存储为 但学生只完成了34小时。

...the integrity constraint would be violated because the record is trying to be stored as a 'junior' but the student has only completed 34 hours.

我如何编写一个强制执行这些规则的约束?

How would I go about writing a constraint which would enforce these rules?

推荐答案

您需要再次使用魔术词 p>

You need to use the magic word and again:

CREATE TABLE students (
....
 , CONSTRAINT IC4 CHECK ( classification = 'junior' AND hours >=55 AND hours <= 84 ) 

我怀疑你会想要其他分类(和使用BETWEEN来定义范围的清晰度)....

I suspect you'll want to have other classifications too, and validate their ranges. Use parentheses and OR to do this. (And use BETWEEN to define the ranges for clarity)....

, CONSTRAINT IC4 CHECK ( ( classification = 'junior' AND hours BETWEEN 55 AND 84 ) 
                       OR ( classification = 'sophomore' AND hours BETWEEN 85 AND 124 )  
                       OR ( classification = 'senior' AND hours > 124 )  
                       OR ( classification = 'fresher' )
                       )                                 

请确保您有一套完整的范围。

Make sure you have a complete set of ranges.

这篇关于Oracle检查完整性约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆