gpt4 book ai didi

sql - 无法从 plpgsql 函数内的动态命名临时表运行 'select into'

转载 作者:行者123 更新时间:2023-11-29 11:55:51 25 4
gpt4 key购买 nike

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

最佳答案

应该是:

EXECUTE sql_string INTO var

关于sql - 无法从 plpgsql 函数内的动态命名临时表运行 'select into',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6333951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com