简体   繁体   中英

Check constraint with condition

I'm wondering if this condition can be done by a check constraint or do I need to create a trigger.

Condition : if student admited date is not null then exam mark is null

Remark: Constaint case OR Trigger

What I tried :

ALTER TABLE ADMITED_TABLE
ADD CONSTRAINT AAAA CHECK
 ( CASE  WHEN  DATEADMITED IS NOT NULL THEN MARK NULL END);

Error:

ORA-00920: invalid relational operator
00920. 00000 -  "invalid relational operator"

A check constraints takes a boolean condition, so you'd have to frame this logic in a form of such a condition:

ALTER TABLE ADMITED_TABLE
ADD CONSTRAINT AAAA CHECK
(dateadmited IS NULL OR mark IS NULL);

I must be misreading David's requirement, because my solution is:

ALTER TABLE admitted_table
    ADD CONSTRAINT aaaa CHECK
            ( (dateadmitted IS NOT NULL
           AND mark IS NULL)
          OR dateadmitted IS NULL);

The following are my test cases:

-- Succeeds
INSERT INTO admitted_table (
           dateadmitted, mark
            )
     VALUES (SYSDATE, NULL);

-- Fails due to check constraint
INSERT INTO admitted_table (
           dateadmitted, mark
            )
     VALUES (SYSDATE, 10);

-- Succeeds
INSERT INTO admitted_table (
           dateadmitted, mark
            )
     VALUES (NULL, 99);

From the description in the question it appears that what you want is a trigger, not a constraint. A constraint lets you verify that values in a table are as you expect them to be; however, a constraint cannot change the value of a column. So if you're just trying to verify that the values supplied match your rules a CHECK constraint is sufficient. If you want to (potentially) change the value of the MARK column you'll need to use a trigger, such as:

CREATE OR REPLACE ADMITED_TABLE_BIU
  BEFORE INSERT OR UPDATE ON ADMITED_TABLE
  FOR EACH ROW
BEGIN
  IF :NEW.DATEADMITED IS NOT NULL THEN
    :NEW.MARK := NULL;
  END IF;
END ADMITED_TABLE_BIU;

Best of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM