我正在尝试编写一个函数,该函数运行一个插入语句,并将表名作为变量,而where子句接受一个数组作为另一个变量。
CREATE OR REPLACE FUNCTION f_dynamic_sql()
RETURNS void
LANGUAGE plpgsql
AS
$body$
DECLARE
rec record;
iterator float4 := 1;
tbl_name text;
BEGIN
DROP TABLE IF EXISTS t_ar; CREATE TEMP TABLE t_ar (reg text, zones text[]);
INSERT INTO t_ar VALUES
('NA', '{"US","UG","UC","UR"}'),
('NE', '{"UK", "SP"}'),
('LA', '{"CA","EC","WC","EC","WC"}');
FOR rec IN SELECT zones from t_ar
LOOP
tbl_name := 'schema.table_' || iterator;
EXECUTE format('INSERT INTO %s
SELECT
DATE_PART(''MONTH'', month)::INT AS month,
SUM(COALESCE(prev_year,0))::INT AS py,
SUM(COALESCE(last_year,0))::INT AS ly
FROM org_table
WHERE load_area IN (SELECT UNNEST(rec.zones))
GROUP BY 1
ORDER BY 1', tbl_name);
iterator := iterator + 1;
END LOOP;
END;
$body$
VOLATILE
COST 100;
这在执行格式之外运行良好,但是我不能将表名放在变量中,但是在执行格式中,它在SQL查询中显示语法错误。 SQL查询可以在外部正常运行。
答案 0 :(得分:1)
您需要在format()
函数中使用占位符和参数。
使用EXECUTE format()
时的实用技巧-使用RAISE NOTICE '%',
代替EXECUTE
并在psql中运行该函数以查看其实际生成的查询。当确定生成的查询正确时,将RAISE NOTICE '%',
替换为EXECUTE
。示例:
...
FOR rec IN SELECT reg, zones FROM t_ar
LOOP
RAISE NOTICE '%', format('
INSERT INTO my_schema.table_%s
SELECT
DATE_PART(''MONTH'', month)::INT AS month,
SUM(COALESCE(prev_year,0))::INT AS py,
SUM(COALESCE(last_year,0))::INT AS ly
FROM org_table
WHERE load_area = ANY (%L)
GROUP BY 1
ORDER BY 1', rec.reg, rec.zones);
END LOOP;
...