Trigger to prevent column value from A to B, and from B to A

All we need is an easy explanation of the problem, so here it is.

I’m trying to create a trigger that prevents a column to be updated as follows:

If column value is "A", it cannot be updated to "B",
and if column value is "B", it cannot be updated to "A".

CREATE OR REPLACE FUNCTION cancelled_order()
    RETURNS trigger
    LANGUAGE plpgsql
AS $function$BEGIN
    IF OLD.status = 'Cancelled' THEN NEW.status != 'Accomplished';
    END IF;
    IF OLD.status = 'Accomplished' THEN NEW.status != 'Cancelled';
    END IF;
    RETURN NEW;
END;
$function$;

CREATE TRIGGER No_cancelled_acomplished
    BEFORE UPDATE OF status
    ON clinical.tb_orders
    EXECUTE PROCEDURE cancelled_order();

The error that comes out is:

Sintaxis error: != 

Any idea, why?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

Based on what you want to accomplish logically, shouldn’t:

IF OLD.status = 'Cancelled' THEN NEW.status != 'Accomplished';
END IF;
IF OLD.status = 'Accomplished' THEN NEW.status != 'Cancelled';
END IF;

actually say something like this?

IF OLD.status = 'Cancelled' AND NEW.status = 'Accomplished' THEN RETURN OLD; -- Set A = A when trying to set it to B
END IF;
IF OLD.status = 'Accomplished' AND NEW.status = 'Cancelled' THEN RETURN OLD; -- Set B = B when trying to set it to A
END IF;

My syntax might be slightly off for PostgreSQL, but my point is isn’t this the kind of logical expression you’re looking for? (You shouldn’t be doing a boolean comparison in the THEN clause, which I think is why it’s mad about the !=.)

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply