Site icon Cool Runnings

Stored procedure to load a table returns no values

I am using PostgreSQL.I have to create a stored procedure that serves to load data from other tables into the table tb_match_by_city_agg. The function doesn’t show errors, but when I select the values of the table the only thing I can see are the titles of the columns. I followed the suggested method of my professor, but I can’t get the correct answer. I’m not sure, but I believe the problem is with the loop. Does anybody know how could I solve this?

DROP TABLE

IF EXISTS euro2021.tb_match_by_city_agg;
    CREATE TABLE euro2021.tb_match_by_city_agg (
        city_code CHAR(5) NOT NULL
        ,city_name CHARACTER VARYING(60) NOT NULL
        ,country_code CHARACTER VARYING(40) NOT NULL
        ,country_name CHARACTER VARYING(60) NOT NULL
        ,referee_count INTEGER NOT NULL
        ,goal_count INTEGER NOT NULL
        ,CONSTRAINT pk_match_by_city_agg PRIMARY KEY (
            city_code
            ,country_code
            )
        );

CREATE
    OR REPLACE FUNCTION euro2021_dw.sp_load_match_by_city_agg ()
RETURNS void AS $$

DECLARE v_row_match_by_city_agg euro2021.tb_match_by_city_agg % rowtype;

BEGIN
    DELETE
    FROM euro2021.tb_match_by_city_agg;
    FOR

    v_row_match_by_city_agg IN

    SELECT ci.city_code
        ,ci.city_name
        ,co.country_code
        ,co.country_name
        ,COALESCE(COUNT(DISTINCT referee_code), 0) AS referee_count
        ,COALESCE(SUM(home_goals + visitor_goals), 0) AS goal_count
    FROM euro2021.tb_city AS ci
    LEFT JOIN euro2021.tb_country AS co ON ci.country_code = co.country_code
    LEFT JOIN euro2021.tb_stadium AS st ON ci.city_code = st.city_code
    LEFT JOIN euro2021.tb_match AS m ON st.stadium_code = m.stadium_code
    GROUP BY ci.city_code
        ,ci.city_name
        ,co.country_code
        ,co.country_name LOOP

    SELECT sp_load_match_by_city_agg(v_row_match_by_city_agg.city_code)
    INTO v_row_match_by_city_agg.goal_count;

    INSERT INTO euro2021.tb_match_by_city_agg
    SELECT v_row_match_by_city_agg.*;
END LOOP;END;$$

LANGUAGE plpgsql;

SELECT *
FROM euro2021.tb_match_by_city_agg

DROP FUNCTION euro2021_dw.sp_load_match_by_city_agg()

Thanks in advance.

Exit mobile version