无法在plpgsql函数中从动态命名的临时表中运行'select into'

时间:2011-06-13 17:31:10

标签: sql postgresql plpgsql

我动态地命名临时表,将一些数据插入到这个动态命名的临时表中。 但我无法将动态命名临时表中的数据恢复到函数变量来进行计算。 如何从/用动态命名的临时表执行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,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;  

1 个答案:

答案 0 :(得分:6)

应该是:

EXECUTE sql_string INTO var