Search code examples
oracleplsqldatabase-trigger

How can I create a trigger in PL/SQL that can create a restriction so that they can only put 1 character?


CREATE OR REPLACE TRIGGER sexo_A
Before update or insert of sexo on ator
for each row 
when (
    if (new.sexo = 'F')
    then
        return 1;
    elseif (new.sexo = 'M')
    then
        return 1;
    else
    then
        return 0;
    end if;)
begin
RAISE_APPLICATION_ERROR('Só pode meter "F" para feminino e "M" para masculino');
end;

What I want to do is to put a restriction when they try to update or insert in the attribute "sexo", and the user can only put the character 'F' (for female) or 'M' (for male).


Solution

  • This is not the job of the trigger. Use a check constraint instead:

    ALTER TABLE ator ADD CONSTRAINT ckgender CHECK (sexo IN ('M', 'F'));
    

    If you really want to abuse the trigger:

    CREATE OR REPLACE TRIGGER trg_sexo
    BEFORE UPDATE OR INSERT OF sexo ON ator
    FOR EACH ROW
    BEGIN
        IF (:NEW.sexo NOT IN ('M', 'F'))
        THEN
            RAISE_APPLICATION_ERROR(-20000, 'Só pode meter "F" para feminino e "M" para masculino');
        END IF;
    END trg_sexo;
    /