Question

Here is my function

    CREATE OR REPLACE FUNCTION stddev_hs_div(div character varying, col character varying)
    RETURNS dec AS
    $BODY$

    BEGIN   
    RETURN 
   cast(stddev($2) AS dec(14,2)) stddev 
   FROM hsgraduation hs 
   INNER JOIN   divandsch ds 
   ON  ds.id=hs.divandschID 
   WHERE hs.disabilityflag='Y' AND ds.divisionname = $1; 
        END;
  $BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;
ALTER FUNCTION count_hs_div(character varying, character varying)
  OWNER TO polisesm;

Then I try to run this query

SELECT * FROM stddev_hs_div('Richmond City', 'diplomarate'); 

But then I keep getting this error

   ERROR:  function stddev(character varying) does not exist
    LINE 1: SELECT cast(stddev($2) AS dec(14,2)) stddev FROM hsgraduatio...
                    ^
    HINT:  No function matches the given name and argument types. You might need to add      explicit type casts.
    QUERY:  SELECT cast(stddev($2) AS dec(14,2)) stddev FROM hsgraduation hs INNER JOIN   divandsch ds on ds.id=hs.divandschID WHERE hs.disabilityflag='Y' AND ds.divisionname = $1
CONTEXT:  PL/pgSQL function "stddev_hs_div" line 5 at RETURN

I can't figure it out, I thought I had already cast it?

Was it helpful?

Solution

Function stddev exists onfly for numeric types, and you try it with varchar:

ERROR:  function stddev(character varying) does not exist

So any casting is absolutely useless because a main problem is elsewhere.

If $2 is a column name, then it is wrong in basic - you need to use a dynamic SQL

CREATE OR REPLACE FUNCTION stddev_hs_div(varchar, varchar)
RETURNS dec AS $$
DECLARE result dec;
BEGIN
  EXECUTE format('SELECT stddev(%I) FROM hsggraduation .. WHERE division_name=$1', $2)
     INTO dec USING $1;
  RETURN dec;
END;
$$ LANGUAGE plpgsql;

You cannot to use a variable as column or table name in normal query in plpgsql ever. When you would to do it, then you have to use dynamic SQL - build a SQL string first, and execute it later.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top