pl/pgSQL 在 EXECUTE 语句中没有参数 $1



我无法解决这个问题:

CREATE OR REPLACE FUNCTION dpol_insert(
    dpol_cia integer, dpol_tipol character, dpol_nupol integer,
    dpol_conse integer,dpol_date timestamp)
  RETURNS integer AS
$BODY$
    DECLARE tabla text := 'dpol'||EXTRACT (YEAR FROM $5::timestamp);
BEGIN
    EXECUTE '
    INSERT INTO '|| quote_ident(tabla) ||' 
    (dpol_cia, dpol_tipol, dpol_nupol, dpol_conse, dpol_date) VALUES ($1,$2,$3,$4,$5)
    ';
END
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;

尝试时

SELECT dpol_insert(1,'X',123456,1,'09/10/2013')

返回下一条消息:

ERROR:  there is no parameter $1
LINE 3: ...tipol, dpol_nupol, dpol_conse, dpol_date) VALUES ($1,$2,$3,$...
                                                             ^
QUERY:  
    INSERT INTO dpol2013 
    (dpol_cia, dpol_tipol, dpol_nupol, dpol_conse, dpol_date) VALUES ($1,$2,$3,$4,$5)
CONTEXT:  PL/pgSQL function "dpol_insert" line 4 at EXECUTE statement

错误 ***

ERROR: there is no parameter $1
SQL state: 42P02
Context: PL/pgSQL function "dpol_insert" line 4 at EXECUTE statement

你在这里有几个问题。眼前的问题是:

错误:没有参数 $1

发生这种情况是因为您交给 EXECUTE 的 SQL 内部$1与主函数体内的$1不同。EXECUTE SQL 中的编号占位符位于 EXECUTE 的上下文中,而不是在函数的上下文中,因此您需要为这些占位符提供一些参数来执行:

execute '...' using dpol_cia, dpol_tipol, dpol_nupol, dpol_conse, dpol_date;
--            ^^^^^

有关详细信息,请参阅手册中的执行动态命令。

下一个问题是你没有从你的函数返回任何RETURNS integer .我不知道你打算归还什么,但也许你的tablea有一个你想归还的系列id。如果是这样,那么你想要更多类似的东西:

declare
    tabla text := 'dpol' || extract(year from $5::timestamp);
    id integer;
begin
    execute 'insert into ... values ($1, ...) returning id' into id using dpol_cia, ...;
    --                                        ^^^^^^^^^^^^  ^^^^^^^
    return id;
end

在您的函数中。

最新更新