0

I try to create function

CREATE OR REPLACE FUNCTION public.my_sql_function3(IN inputval integer)
  RETURNS TABLE("ID" integer, name character varying, cnt integer) AS
$BODY$
  select t.id, t.name, CAST(count(*) AS INTEGER)
  from test t
  where t.id < inputval
  group by t.id, t.name $BODY$
  LANGUAGE plpgsql VOLATILE;

and get error:

ERROR: syntax error at or near "select"

LINE 4: select t.id, t.name, CAST(count(*) AS INTEGER)

How to fix it?

1

1 Answer 1

1

You have defined the function to be a PL/pgSQL function but your syntax is for a plain SQL function.

You need to use

LANGUAGE sql
Sign up to request clarification or add additional context in comments.

3 Comments

The added remark is incorrect. The cast to integer is necessary. count(*) returns bigint, which would raise an error.
@ErwinBrandstetter: wouldn't that cast happen "automatically" because the return column is defined as integer in the returns table() part?
CREATE FUNCTION accepts data types where at least an implicit cast is registered (like between varchar and text). But the cast from bigint to int is only assignment (potential overflow!). Details: stackoverflow.com/a/21051215/939860

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.