Question

I have written a PostgreSQL function which is being called from Jasper iReport for dashboards. When I try and execute the same function manually in pgAdmin I get an error for invalid syntax for type numeric. Please find my Function which is mentioned below:

CREATE OR REPLACE FUNCTION revenue_dm.trendQuery( IN monthin integer, IN yearin integer  )
  RETURNS TABLE(month1 numeric,year1 numeric,month2 numeric,year2 numeric,month3   numeric,year3 numeric ) AS
$BODY$
       DECLARE

        BEGIN

           month1='select extract (month from (select concat(monthin,''-'',15,''-'',yearin)::date)-30)::numeric';
           month2='select extract (month from (select concat(monthin,''-'',15,''-'',yearin)::date)-60)::numeric';
           month3='select extract (month from (select concat(monthin,''-'',15,''-'',yearin)::date)-90)::numeric';
           year1= 'select extract (year from (select concat(monthin,''-'',15,''-'',yearin)::date)-30)::numeric';
           year2= 'select extract (year from (select concat(monthin,''-'',15,''-'',yearin)::date)-60)::numeric';
           year3= 'select extract (year from (select concat(monthin,''-'',15,''-'',yearin)::date)-90)::numeric';

          RETURN QUERY EXECUTE month1;
          RETURN QUERY EXECUTE month2;
          RETURN QUERY EXECUTE month3;
          RETURN QUERY EXECUTE year1;
          RETURN QUERY EXECUTE year2;
          RETURN QUERY EXECUTE year3;
    END;
    $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100
  ROWS 1000;

I am using the following query to execute my function in pgAdmin.

 SELECT revenue_dm.trendQuery(04,2014);

After executing the function, this is the error that I am getting:

ERROR:  invalid input syntax for type numeric: "select extract (month from (select concat(monthin,'-',15,'-',yearin)::date)-30)::numeric"
CONTEXT:  PL/pgSQL function revenue_dm.trendquery(integer,integer) line 6 at assignment

I am not able to debug where in my code am I going wrong in using the dynamic SQL in this function.

Can anyone please help me out in finding out where am I going wrong in this particular function.

Was it helpful?

Solution

  1. You cannot use outer variables in dynamic sql. Use format() or some similar escape mechanism; or use the USING clause for EXECUTE (preferred)
  2. RETURNS TABLE(month1 numeric ... is equal to define an OUT parameter, which is month1 numeric. In that point of view, you cannot assign a query string to that variable, Postgres will fail trying to parse it as numeric.

Just run a single

RETURN QUERY EXECUTE 'SELECT <multiple fields> ...' USING monthin, yearin;

Edit: just realized, you shouldn't do a dynamic query at all (there no need for them here)

Just run a single

RETURN QUERY SELECT <multiple fields> ...;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top