Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 625
stefmex Avatar asked Oct 10 '13 17:10

stefmex


1 Answers

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.

like image 158
mu is too short Avatar answered Nov 05 '22 04:11

mu is too short