gpt4 book ai didi

postgresql - 将函数应用于另一个函数内的临时表

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

我不熟悉在 postgresql 中创建函数。我使用的版本比较旧。它是 8.2.15(不是我的选择,而是我的组织)。以下示例尝试将一个函数应用于另一个函数中的临时表。

-- First function 
create or replace function inner_func(_tbl anyelement)
RETURNS void AS
$$
BEGIN
EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN d_amount INTEGER';
EXECUTE 'UPDATE ' || _tbl || ' SET d_amount = 2* amount';
RETURN;
END;
$$
LANGUAGE plpgsql volatile;

-- Second function
CREATE OR REPLACE FUNCTION outer_func()
RETURNS void AS
$$
BEGIN
DROP TABLE IF EXISTS my_temp;
CREATE TEMP TABLE my_temp
(id serial primary key,
amount integer
);
INSERT into my_temp (amount) values (10),(20);

-- now apply the inner_func right here
EXECUTE 'SELECT inner_func(' || quote_ident('my_temp') || ')';

RETURN;
END;
LANGUAGE plpgsql volatile;

当我运行时

SELECT outer_func();

它吐出一个错误:

column "my_temp" does not exist

但是,如果我像下面这样单独使用 inner_func,它就会起作用:

create temp table my_temp2
(id serial primary key,
amount integer
);
INSERT INTO my_temp2 (amount) values (10),(20);
SELECT inner_func(quote_ident('my_temp2'));
SELECT * from my_temp2;

id amount d_amount
1 10 20
2 20 40

如何让这个 inner_func 在 outer_func 中工作?有什么想法吗?

最佳答案

看来问题出在这里:

EXECUTE 'SELECT inner_func(' || quote_ident('my_temp') || ')';

=>

EXECUTE 'SELECT inner_func(quote_ident(' || quote_literal('my_temp') || '));';

DBFiddle Demo

关于postgresql - 将函数应用于另一个函数内的临时表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45657402/

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