无法从 plpgsql 函数中的动态命名临时表运行“选择进入”
Posted
技术标签:
【中文标题】无法从 plpgsql 函数中的动态命名临时表运行“选择进入”【英文标题】:Cannot run 'select into' from dynamic-named temporary table within plpgsql function 【发布时间】:2011-06-13 17:31:09 【问题描述】:我正在动态命名临时表,将一些数据插入到这个动态命名的临时表中。 但我无法将动态命名临时表中的数据取回函数变量来进行计算。 如何从动态命名的临时表/使用动态命名的临时表在 plpgsql 函数中执行“选择进入 ....”?
drop table dummy;
drop table mytable;
create table dummy (id bigint,parent_id bigint);
insert into dummy values(600,null);
insert into dummy values(12,600);
insert into dummy values(700,null);
DROP FUNCTION total_test(bigint,text,text,date,bigint[],text);
CREATE OR REPLACE FUNCTION total_test(bigint,text,text,date,dep bigint[],tname text) RETURNS double precision AS '
DECLARE pid BIGINT;
DECLARE total DOUBLE PRECISION;
DECLARE array_len int;
DECLARE myDepIds bigint[];
BEGIN
IF dep IS NOT NULL THEN
total :=0;
array_len := array_upper(DEP, 1);
EXECUTE ''CREATE TEMPORARY TABLE '' || tname || '' (dep_id bigint )'';
FOR i IN 1 .. array_len
LOOP
EXECUTE ''INSERT INTO '' || tname || '' values (''|| DEP[i] ||'')'';
select into pid id from dummy where parent_id in (DEP[i]);
IF pid IS NOT NULL THEN
EXECUTE ''INSERT INTO '' || tname || '' values (''|| pid || '')'';
END IF;
END LOOP;
--works where tname:=''mytable''; select into myDepIds array(select distinct(dep_id) from mytable where dep_id is not null);
--not working; EXECUTE ''select into myDepIds array(select distinct(dep_id) from '' || $7 || '' where dep_id is not null)'';
--not working; EXECUTE ''select into myDepIds array(select distinct(dep_id) from '' || tname || '' where dep_id is not null)'';
EXECUTE ''select into '' || myDepIds || '' array(select distinct(dep_id) from '' || tname || '' where dep_id is not null)'';
--not working; EXECUTE ''select into cast(myDepIds as bigint[]) array(select distinct(dep_id) from '' || tname || '' where dep_id is not null)'';
--calculation....
--EXECUTE ''DROP TABLE '' || tname;
RETURN total;
END IF;
END;
' LANGUAGE plpgsql;
select total_test(11269, 'sales', 'A', date('06/02/2011'), ARRAY[600], 'mytable') as value;
select * from mytable;
【问题讨论】:
你可以在DBA.stackexchange.com问这个 【参考方案1】:应该是:
EXECUTE sql_string INTO var
【讨论】:
EXECUTE ''select array(select distinct(dep_id) from '' || tname || '' where dep_id is not null)'' into myDepIds ;以上是关于无法从 plpgsql 函数中的动态命名临时表运行“选择进入”的主要内容,如果未能解决你的问题,请参考以下文章
Postgresql:对 plpgsql 中的临时表执行更新不起作用
对于表中的行,将行保存在临时表中以在 plpgsql 的选择查询中使用其数据