gpt4 book ai didi

postgresql - 将选择值分配给变量到 PostgreSQL 9.3 函数中的执行

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

考虑这样一个函数:

CREATE OR REPLACE FUNCTION public.foo(
string1 character varying
)
RETURNS integer AS
$BODY$
DECLARE
id1 INTEGER;

BEGIN

id1 := (SELECT id FROM mytable WHERE mycolumn = string1);
END;
......

它工作正常,我得到了用于函数其他部分的 id1 值。

现在,我想重写函数并传递一个充当表标识符的名称。

  CREATE OR REPLACE FUNCTION public.foo(
string1 character varying,
tablecode character varying --new argument
)
RETURNS integer AS
$BODY$
DECLARE
id1 INTEGER;

BEGIN
.....

现在,我尝试获取 id1 值和错误:

EXECUTE FORMAT('id1 := (SELECT id FROM %I WHERE mycolumn = %s)', tablecode||'_Conceptos', quote_literal(string1));

错误:

ERROR:  syntax error at or near "id1"
LINE 1: id1 := (SELECT id FROM "CENZANO_Conceptos" WHERE codigo ...
^
QUERY: id1 := (SELECT id FROM "CENZANO_Conceptos" WHERE codigo = 'CENZANO')

--第二次尝试

 EXECUTE FORMAT ('SELECT %I.id INTO id1 FROM %I WHERE mycolumn = %s', tablecode||'_Conceptos',tablecode||'_Conceptos',quote_literal(string1));

END;
......

错误:

ERROR:  EXECUTE of SELECT ... INTO is not implemented
HINT: You might want to use EXECUTE ... INTO or EXECUTE CREATE TABLE ... AS instead.

提前致谢

最佳答案

你可以使用INTO:

EXECUTE FORMAT('(SELECT id FROM %I WHERE mycolumn = %s)'
, tablecode||'_Conceptos', quote_literal(string1)) INTO id1;

关于postgresql - 将选择值分配给变量到 PostgreSQL 9.3 函数中的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52238002/

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