Search code examples
postgresqlexecuteusing-statement

No parameter $2 when using EXECUTE format( ... ) USING (param1, param2)


I am attempting to use the EXECUTE format( ... ) USING (param1, param2, ... ) feature within a postgres function. The relevant snippet of code is as follows

  EXECUTE format('select json_agg(json_build_object(''Attribute'', x.attr, ''Aggregate'',x.agg)) 
                    from 
                     ( select %I as attr, round(sum(value),6) as agg 
                         from schema_name.seperate_function($1,$2)
                        group by attr
                        order by agg desc ) x', columnNames[1])
  USING (param1, param2)

Where

columnNames[1], param1, & param2

are previously defined in the function. In fact, param1 & param2 are input to the function and declared in the beginning of the function's body If that's at all relevant.

DECLARE
param1 ALIAS FOR $1;
param2 ALIAS FOR $2;

Naturally I haven't actually called my parameter's param1 or 2, nor is schema_name.seperate_function the actual function name that this piece of code is referencing. Regardless, when I execute this, I get the following error :

ERROR:  there is no parameter $2
LINE 4: ...      from schema_name.seperate_function($1,$2)

If instead, If I replace $2 in the formatted query string with a hard coded value, and get rid of param2 from the USING claus, it works fine. Initially, I thought it was syntax related, but after looking at The accepted answer here

for example, I don't see any issue with my syntax. Any suggestion's here would be greatly appreciated, thanks.


Solution

  • You are passing row (param1, param2) as first parameter and then have no second parameter. If you replace $2 with hardcoded value and leave (param1, param2) you will see that it is passing row into $1 instead of param1.

    What you need to do is this: USING param1, param2 no parenthesis.