3

I am having a problem with a trigger. I created a trigger and a function for when performing an INSERT update a field in the same table. Is returning:

Error: function "loss_func" in FROM has return type trigger that is not supported LINE 1: SELECT * FROM table.loss_func ()

Function

CREATE OR REPLACE FUNCTION loss_func()
  RETURNS trigger AS $loss_func$
  BEGIN
     NEW.dt_creation := to_char(now(), 'YYYY-MM-DD');   

     RETURN NULL;
  END;
  $loss_func$ LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION loss_func()
   OWNER TO postgres;

Trigger

CREATE TRIGGER tgr_loss
  AFTER INSERT ON loss
  FOR EACH ROW
  EXECUTE PROCEDURE loss_func();

What am I doing wrong?

2
  • SELECT * FROM table.loss_func () why are you doing this ? what are you trying to select with this? this is what causes the error. Remove it and it will try to create your trigger. The execution stopped at the first line Commented Dec 4, 2017 at 19:14
  • AFTER triggers can't return NULL. (can't alter values either) Commented Dec 8, 2017 at 5:11

1 Answer 1

4

A working version of your code. - The trigger now fires BEFORE insert and updates the value of dt_creation and returns the NEW version of the record :

drop table loss;

create table loss (
id int ,
dt_created varchar);

CREATE OR REPLACE FUNCTION loss_func()
  RETURNS trigger AS $loss_func$
  BEGIN
     NEW.dt_created := to_char(now(), 'YYYY-MM-DD');   
     RETURN NEW;
  END;
  $loss_func$ LANGUAGE plpgsql VOLATILE
  COST 100;

ALTER FUNCTION loss_func()
   OWNER TO postgres;

CREATE TRIGGER tgr_loss
  BEFORE INSERT ON loss
  FOR EACH ROW
  EXECUTE PROCEDURE loss_func();

insert into loss(id) values(1);

Another solution that i can propose to avoid the usage of a trigger is to use a default value for dt_creation when you create the table (and use timestamp instead of storing the date as varchar) :

...
dt_creation timestamp default now(),
...

or you can alter your table to set the default value to now() :

alter table loss 
alter column dt_creation set default now(); 
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.