Search code examples
sqloracleplsqldatabase-trigger

Oracle PL/SQL check an input against 3 constants


I need to check a variable (Subject Name) and make sure that it is 1 of the following before inserting or updating - Software, Computing or Business.

This is for a piece of Uni work and the lecturers are awful so any help would be appreciated.

I have the following code but it does not seem to work.

create or replace trigger subject_name_check
  before insert or update on Student
  FOR EACH ROW
  WHEN (NEW.SUBJECT <> 'Software' or 'Computing' or 'Business')
begin
  DBMS_OUTPUT.PUT_LINE('INVALID INPUT');
end;

Solution

  • All you are doing is printing a message, which the client may or may not be configured to see. You aren't stopping the insert from completing.

    You could raise an exception instead:

    create or replace trigger subject_name_check
      before insert or update on Student
      FOR EACH ROW
      WHEN (NEW.SUBJECT NOT IN ('Software', 'Computing', 'Business'))
    begin
      RAISE_APPLICATION_ERROR(-20001, 'INVALID INPUT');
    end;
    

    I fixed the comparison logic too - you can't compare one thing with multiple others in the way you had attempted.

    Quick demo:

    create table student (subject varchar2(20));
    
    create or replace trigger subject_name_check
      before insert or update on Student
      FOR EACH ROW
      WHEN (NEW.SUBJECT NOT IN ('Software', 'Computing', 'Business'))
    begin
      RAISE_APPLICATION_ERROR(-20001, 'INVALID INPUT');
    end;
    /
    
    insert into student (subject) values ('Software');
    
    1 row inserted.
    
    insert into student (subject) values ('Spanish');
    
    ORA-20001: INVALID INPUT
    ORA-06512: at "MYSCHEMA.SUBJECT_NAME_CHECK", line 2
    

    But this should really be done with a check constraint, not with a trigger:

    drop trigger subject_name_check;
    
    alter table student add (
      constraint subject_name_check check (
        subject in ('Software', 'Computing', 'Business'))
    );
    
    insert into student (subject) values ('Computing');
    
    1 row inserted.
    
    insert into student (subject) values ('Physics');
    
    ORA-02290: check constraint (MYSCHEMA.SUBJECT_NAME_CHECK) violated
    

    ... or even better with a foreign key relationship to another table with a valid list of subjects.