1

I want to create a plpgsql function that will be called by a BEFORE INSERT trigger. This function is updating a column based on value from another column.

Here is the code:

CREATE OR REPLACE FUNCTION Xupd_cat_prop()
                           RETURNS TRIGGER
AS
$$ 
DECLARE categ_prop varchar;
BEGIN
    kateg_prop := CASE
        WHEN new.cat_tarif = 'domestic_1' OR new.cat_tarif = 'domestic_2' THEN new.class = 'DOM'
        WHEN new.cat_tarif = 'nondomestic_1' THEN new.class = 'NONDOM'
        WHEN new.cat_tarif = 'industry' THEN new.class = 'IND'
    END;
  RETURN new; 
END;
$$ 
LANGUAGE plpgsql;

But this doesn't work. I am using Postgres 16. The error is somewhere with the WHEN clause.

0

1 Answer 1

3

You use SQL CASE statement. The WHEN clause can contains only expressions:

kateg_prop := CASE
        WHEN new.cat_tarif = 'domestic_1' OR new.cat_tarif = 'domestic_2' THEN 'DOM'
        WHEN new.cat_tarif = 'nondomestic_1' THEN 'NONDOM'
        WHEN new.cat_tarif = 'industry' THEN 'IND'
    END;

Although the syntax is similar, there are significant differences between SQL (functional) and PL/pgSQL (procedural) CASE:

SQL CASE:

 CASE var WHEN expr THEN expr [...] END

PLpgSQL CASE

  CASE var WHEN expr THEN plpgsql statement [...] END CASE

SQL CASE returns a value, PL/pgSQL CASE executes statements.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.