问题描述
||
我正在动态命名临时表,将一些数据插入此动态命名的临时表。
但是我无法从动态命名的临时表中获取数据到函数变量中进行计算。
我如何在带有动态命名的临时表的plpgsql函数中执行\'select into .... \'?
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,date,bigint[],text);
CREATE OR REPLACE FUNCTION total_test(bigint,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;
解决方法
应该:
EXECUTE sql_string INTO var