I need to learn more about postgres but I am trying to write a function that links to a trigger in my postgres db. Normally the functions I write work fine, however, this particular function keeps returning errors around the syntax at the end of my output.
I have a fixtures table with a column called 'Result'. I want to read the scores from the fixture e.g. Wolves 0:0 Ipswich, and trigger into Result 'Draw'.
The query I am writing is as follows:
CREATE OR REPLACE FUNCTION sppullscoretrigger()
RETURNS trigger
SECURITY DEFINER
AS $BODY$
DECLARE
payload text;
BEGIN
SELECT NEW.Home_Side_Score, NEW.Away_Side_Score FROM Fixtures;
IF NEW.Home_Side_Score is NULL or NEW.Away_Side_Score is NULL THEN NEW.Result = 'TBC';
IF NEW.Home_Side_Score = NEW.Away_Side_Score THEN NEW.Result = 'Draw';
IF NEW.Home_Side_Score > NEW.Away_Side_Score THEN NEW.Result = 'Home_Win';
IF NEW.Home_Side_Score < NEW.Away_Side_Score THEN NEW.Result = 'Away_Win';
ELSE NEW.Result = 'Error';
END IF;
RETURN NEW;
END
$BODY$
LANGUAGE plpgsql
CREATE TRIGGER trgscore
BEFORE INSERT OR UPDATE
ON Fixtures
FOR EACH ROW
EXECUTE PROCEDURE sppullscoretrigger();
I have only written basic functions before but I am really struggling with getting this trigger to work.
;after the trigger function (and before thecreate trigger). Also:SELECT NEW.Home_Side_Score, NEW.Away_Side_Score FROM Fixtures;will select all rows from the tablefixturesbut with constant values for each row. You do not need that select at all. In a row level trigger you can just access thenewandoldrecordscreate tablestatement for the table. But it's probably better to ask a new question for that problem.