0

I have two table, with different columns, and I have to create a function to update the second table with the information from the first when the columns year match with the given year and group all in gender groups.

Here I put my code but I don't know if it is okay because the pgAdmin4 returns me an error because of the $$ symbols, although I am trying to solve it.

BEGIN WORK;

CREATE OR REPLACE FUNCTION update_report(p_year INTEGER) 
RETURNS SETOF report1 AS $$
DECLARE report report1;
BEGIN
UPDATE report1 SET m.num=t_num, m.na=t_na, m.nd=t_nd, m.birth=t_birth
FROM report2 m
    FULL JOIN report1
    ON p_year= m.year
GROUP BY m.gender);

   --In case there are any film in the specified year
IF NOT FOUND THEN
    RAISE EXCEPTION  ‘’%: No film exists in this year’’, -746;
END IF;
RETURN report;

END;
$$ LANGUAGE plpgsql;

COMMIT WORK;

Can someone just tell if it is okay? Thanks

2
  • 1
    the group by without any aggregates is most definitely wrong. And you have a stray ) after it. that's the obvious syntax errors I can see Commented Nov 24, 2019 at 9:59
  • Creates a cross join because I previously declare report1? Commented Nov 24, 2019 at 10:01

1 Answer 1

1

I am not sure what "group by gender" is supposed to mean, but I think you are looking for a simple UPDATE.

Note that you should not repeat the target table in the FROM clause of an UPDATE statement.

Quote from the manual

Note that the target table must not appear in the from_list, unless you intend a self-join

You didn't show us any sample data and expected results or the structure of the tables, so I can only guess, what exactly you want, but something like this maybe:

UPDATE report1 r1
   SET num = r2.t_num, 
       na = r2.t_na, 
       nd = r2.t_nd
       birth = r.t_birth
FROM report2 r2
WHERE r1.year = r2.year
  AND r1.gender = r2.gender
  AND r1.year = p_year= m.year;

If you want to return all rows that have been changed, then you can use the RETURNING clause. You don't need a declare for that. Using language sql instead of PL/pgSQL makes this even simpler:

CREATE OR REPLACE FUNCTION update_report(p_year INTEGER) 
   RETURNS SETOF report1 
AS $$
  UPDATE report1 r1
     SET num = r2.t_num, 
         na = r2.t_na, 
         nd = r2.t_nd
         birth = r.t_birth
  FROM report2 r2
  WHERE r1.year = r2.year
    AND r1.gender = r2.gender
    AND r1.year = p_year= m.year
  RETURNING r1.*; --<< return all modified rows
$$ 
LANGUAGE sql;
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.