Oracle Check Integrity Constraint

家住魔仙堡 提交于 2019-12-14 02:31:12

问题


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).

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);  

...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?


回答1:


You need to use the magic word and again:

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

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.




回答2:


Once you have create table:

Then add check constraint using the alter statement given below:

ALTER TABLE Students
ADD CONSTRAINT IC4 (classification='junior' AND hours >=55 AND hours <= 84 );

Now when you try to insert the below statement:

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

It will not allow to insert the above statement.



来源:https://stackoverflow.com/questions/14669174/oracle-check-integrity-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!