0

I'm designing a PostgreSQL schema and I want to create a rule that if the user doesn't enter a value for Column C then i make the value of column C COALESCE(COLUMN A, COLUMN B). I've tried table update, and a trigger but there must be something wrong with the logic, I'd appreciate your help - thanks.

I have tried:

1.

update Mytable 
    set ColC=
    case when ColC is NULL then COALESCE(ColA,ColB)
    else ColC;

2.

CREATE TRIGGER ColC_VIOLATION
BEFORE INSERT OR UPDATE OF ColC
ON Mytable FOR EACH ROW
WHEN ColC is NULL then COALESCE(ColA,ColB)

3.

CREATE OR REPLACE FUNCTION ColC_func() RETURNS trigger AS 
$$
BEGIN
UPDATE Mytable
    set ColC=
    case when ColC is NULL then  COALESCE(ColA,ColB)
    else ColC ;
END
$$
LANGUAGE PLPGSQL;

1 Answer 1

1

you don't need an UPDATE statement in the trigger, just assign the value:

CREATE OR REPLACE FUNCTION ColC_func() RETURNS trigger AS 
$$
BEGIN
   NEW.colc := COALESCE(NEW.cola, NEW.colb);
   RETURN NEW;
END
$$
LANGUAGE PLPGSQL;

And make the trigger only fire if colc is null:

CREATE TRIGGER ColC_VIOLATION
  BEFORE INSERT OR UPDATE on mytable
  FOR EACH ROW execute procedure colc_func()
  WHEN ColC is NULL;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.