Pl/pgSQL there is no parameter $1 in EXECUTE statement

南楼画角 提交于 2019-12-06 08:35:24

问题


I can't solve this:

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;

When trying

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

return next message:

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 ***

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

回答1:


You have a couple problems here. The immediate problem is:

ERROR: there is no parameter $1

That happens because $1 inside the SQL that you're handing to EXECUTE isn't the same as $1 inside the main function body. The numbered placeholders within the EXECUTE SQL are in the context of the EXECUTE, not in the function's context so you need to supply some arguments to EXECUTE for those placeholders:

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

See Executing Dynamic Commands in the manual for details.

The next problem is that you're not returning anything from your function which RETURNS integer. I don't know what you intend to return but maybe your tablea has a SERIAL id that you'd like to return. If so, then you want something more like this:

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

in your function.



来源:https://stackoverflow.com/questions/19302098/pl-pgsql-there-is-no-parameter-1-in-execute-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!