我正在尝试优化一个具有7个WITH
临时表的函数,充当排序机制,从初始临时表/排序级联到下一个临时表,直到最后一个,例如第7个临时表/排序
Gist here:必须禁止使用此类代码。
我正在尝试将WITH
排序替换为真正的临时表,例如CREATE TEMPORARY TABLE <table_name> AS SELECT col1 FROM another_table;
。目的是提高性能,因为当前形式的查询非常慢。
这是我提出的改变
CREATE OR REPLACE FUNCTION report.get_sa001(
IN "date_D" timestamp without time zone,
IN "date_F" timestamp without time zone,
IN frequence integer)
RETURNS TABLE(
"Period_date" timestamp without time zone,
"Site" character varying,
"Customer_code" character varying,
"Internal_reference" character varying,
"InvoiceNumber" character varying,
"Value_in_currency" numeric,
"Value_in_EUR" numeric,
"Value_Budget_in_EUR" numeric,
"Selling_price_CUR" numeric,
"Selling_price_EUR" numeric,
"Currency_code" character varying,
"Selling_quantity" numeric,
"Variance_price_CUR" numeric,
"Variance_price_EUR" numeric,
"Variance_value_CUR" numeric,
"Variance_value_EUR" numeric,
"Selling_date" timestamp without time zone) AS
$BODY$
DECLARE
p_debut timestamp without time zone;
DECLARE
p_fin timestamp without time zone;
BEGIN
p_debut = dw.get_period_end("date_D", "frequence");
p_fin = dw.get_period_end("date_F", "frequence");
RETURN QUERY
CREATE TEMPORARY TABLE "dates_1" AS
SELECT
p_debut::date + n AS "date",
dw.period_frequency(p_debut::date + n) AS "frequency"
FROM generate_series(0, p_fin::date - p_debut::date) AS x(n)
WHERE (dw.period_frequency(p_debut::date + n) & frequence != 0);
SELECT * FROM "dates_1"; -- Thanks to Vao Tsun
END;
$BODY$
LANGUAGE plpgsql STABLE
COST 100
ROWS 1000;
函数的创建很好但是以这种方式运行函数
SELECT * FROM report.get_sa001('2017-01-01'::date, '2017-01-31'::date, 32)
这就是我所拥有的
ERROR: cannot open query CREATE TABLE AS like cursor
État SQL :42P11
Contexte : fonction PL/pgsql report.get_sa001(timestamp without time zone,timestamp without time zone,integer), ligne 11 à RETURN QUERY
我尝试用CREATE TEMPORARY TABLE
替换SELECT * INTO TEMPORARY TABLE
。创建再次正常,但运行时出现相同的错误。
检查SO的存档,听起来PLPGSQL禁止使用临时表(检查here)。
如果您有任何想法,他们会受到欢迎。
由于
答案 0 :(得分:1)
在函数中使用create temporary table没有任何问题:
t=# create or replace function so37() returns table (i int) as
$$
declare
begin
create temporary table a as select 2;
return query select * from a;
end;
$$ language plpgsql
;
CREATE FUNCTION
t=# select * from so37();
i
---
2
(1 row)
但是必须对它们进行维护,例如在当前示例中,如果存在则缺少drop table,或者不应该插入应该插入的create table,因为如果你不这样做,第二次运行将失败:
t=# select * from so37();
ERROR: relation "a" already exists
CONTEXT: SQL statement "create temporary table a as select 2"
PL/pgSQL function so37() line 4 at SQL statement
我相信CTE是在函数中创建临时表的更好选择......