Cannot run 'select into' from dynamic-named temporary table within plpgsql function
I am dynamcially naming temporary table, inserting some data to this dynamic-named temporary table. But I am not able to get back the data from dynamic-named temporary table to function variable to do my calculation. How can I execute 'select into ....' inside plpgsql function from/with dynamic-named temporary table?
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 .. ar开发者_C百科ray_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;
Should be:
EXECUTE sql_string INTO var
精彩评论