Thread: Using arguments with functions

Using arguments with functions

From
"Robert Fitzpatrick"
Date:
While this function works when hard coded, the following will not when
trying the same thing with a argument. Can someone point to me what I'm
doing wrong?

CREATE OR REPLACE FUNCTION "public"."test" () RETURNS varchar AS'
DECLARE
  var1 varchar;

BEGIN
  var1 = chr( (ascii(''a'') + 1) );
  return var1;
END;
'LANGUAGE 'plpgsql' VOLATILE RETURNS NULL ON NULL INPUT SECURITY INVOKER;

ohc=> select test();
 test
------
 b
(1 row)

This does not work:

CREATE OR REPLACE FUNCTION "public"."get_next" (varchar) RETURNS varchar AS'
DECLARE
  var1 alias for $1;

BEGIN
  var1 = chr( (ascii(var1) + 1) );
  return var1;
END;
'LANGUAGE 'plpgsql' VOLATILE RETURNS NULL ON NULL INPUT SECURITY INVOKER;

ohc=> select get_next('a');
ERROR:  "$1" is declared CONSTANT
CONTEXT:  compile of PL/pgSQL function "get_next" near line 5

--
Robert


Re: Using arguments with functions

From
Oliver Elphick
Date:
On Sat, 2004-07-10 at 20:50, Robert Fitzpatrick wrote:
> While this function works when hard coded, the following will not when
> trying the same thing with a argument. Can someone point to me what I'm
> doing wrong?
...

> This does not work:
>
> CREATE OR REPLACE FUNCTION "public"."get_next" (varchar) RETURNS varchar AS'
> DECLARE
>   var1 alias for $1;
>
> BEGIN
>   var1 = chr( (ascii(var1) + 1) );
...
> ERROR:  "$1" is declared CONSTANT

You are trying to change the passed parameter.

Instead do

        DECLARE
           var1   varchar;
        BEGIN
           var1 = chr( (ascii($1) + 1) );

which I think should work.

--
Oliver Elphick                                          olly@lfix.co.uk
Isle of Wight                              http://www.lfix.co.uk/oliver
GPG: 1024D/A54310EA  92C8 39E7 280E 3631 3F0E  1EC0 5664 7A2F A543 10EA
                 ========================================
     "Delight thyself also in the LORD; and he shall give
      thee the desires of thine heart."
                                  Psalms 37:4


Re: Using arguments with functions

From
Tom Lane
Date:
"Robert Fitzpatrick" <robert@webtent.com> writes:
> CREATE OR REPLACE FUNCTION "public"."get_next" (varchar) RETURNS varchar AS'
> DECLARE
>   var1 alias for $1;
> BEGIN
>   var1 = chr( (ascii(var1) + 1) );
> ...
> ohc=> select get_next('a');
> ERROR:  "$1" is declared CONSTANT
> CONTEXT:  compile of PL/pgSQL function "get_next" near line 5

plpgsql does not allow you to overwrite an argument value.

            regards, tom lane