我有一个update_total
看起来像这样的函数:
CREATE OR REPLACE FUNCTION update_total (table_name CHARACTER VARYING, year CHARACTER(4), donor_type CHARACTER VARYING, donor_code CHARACTER(5)) RETURNS VOID AS $$
DECLARE
table_name ALIAS FOR $1;
year ALIAS FOR $2;
donor_type ALIAS FOR $3;
donor_code ALIAS FOR $4;
query_statement TEXT;
BEGIN
query_statement :=
'
UPDATE gha.' || table_name || '
SET "' || year || '" = "' || year ||'_total"
FROM gha.' || table_name || ' "' || year || '",
(
SELECT
donor_type
, COALESCE(SUM("' || year || '"), 0) AS "' || year ||'_total"
FROM gha.' || table_name || '
WHERE donor_type = ''' || donor_type || '''
GROUP BY donor_type
) "new_data"
WHERE
gha.' || table_name || '.donor_code = ' || CAST(donor_code AS INT) || ';'
;
EXECUTE query_statement;
END;
$$ LANGUAGE plpgsql;
它更新表中包含聚合值的行,我称它为,例如,如下所示:
SELECT update_total ('bilateral_oda_dac_1', '1990', 'Multilateral', '20002');
它更新的表设置为每年都有一个范围内的列,即:
Column | Type
------------+-------------------
donor_code | smallint
donor_name | character varying
donor_type | character varying
1990 | numeric
1991 | numeric
1992 | numeric
...
使用此功能,我一次只能更新一列中的聚合值,但我希望能够一次更新一系列列,大致如下:
CREATE FUNCTION update_all_total ()
RETURNS void LANGUAGE plpgsql AS
$BODY$
BEGIN
FOR i IN 1990 .. 1995
LOOP
PERFORM update_total ('bilateral_oda_dac_1', i, 'DAC', '20001');
END LOOP;
END;
$BODY$;
(我用这篇文章让我开始:https ://stackoverflow.com/questions/11164409/sql-call-function-multiple-times-in-a-loop-postgres-8-3 )。上面截断的代码不起作用,因为我正在使用的函数将字符串作为输入,并且我向它传递了一个整数。我如何设置循环以便将字符串传递给我在其中调用的函数?
你可以使用
to_char()
,或者可以使用 cast
::char(4)
。