4

I have a function func1() which returns integer.

I want to write another function func2(mode integer) which can return func1() reults or do some more stuff. The return value of func1() is of type INTEGER.

something like this:

CREATE OR REPLACE FUNCTION func2(mode integer)
  RETURNS integer AS
$$
begin
     if mode=1 then
       return func1();  -- NOT plpgsql syntax
     end if;

     more stuff .....

     return 2;
end
$$
LANGUAGE plpgsql VOLATILE

my question is how to do return func1(); ?

I know I can do :

select func1() into temp;
return temp;

but I was wondring if there is a more elegent way to do that.

ban
  • 187
  • 1
  • 1
  • 10
  • 2
    `return func1();` works for me: http://sqlfiddle.com/#!15/18442/1 What is the error you get? –  Sep 06 '16 at 11:12

1 Answers1

1

All of these work:

Option 1:

CREATE OR REPLACE FUNCTION func2(mode integer)
    RETURNS integer AS
$BODY$
DECLARE 
    _result integer;
BEGIN
    _result = 2;
     IF mode=1 THEN
       _result = func1();
     END IF;

     --more stuff .....

     RETURN _result;
END
$BODY$
    LANGUAGE plpgsql VOLATILE COST 100;

Option 2:

CREATE OR REPLACE FUNCTION func2(mode integer)
    RETURNS integer AS
$BODY$
BEGIN
     IF mode=1 THEN
       RETURN func1();
     END IF;

     --more stuff .....

     RETURN 2;
END
$BODY$
    LANGUAGE plpgsql VOLATILE COST 100;
Boris Schegolev
  • 3,601
  • 5
  • 21
  • 34
  • Using `:=` as the assignment operator is preferred over the simple `=` –  Sep 06 '16 at 11:37
  • @a_horse_with_no_name why is it prefered? – ban Sep 06 '16 at 11:42
  • I never liked the Pascal notation. Just a personal preference :) – Boris Schegolev Sep 06 '16 at 11:42
  • Up until 9.3 this was actually the only documented assignment operator: https://www.postgresql.org/docs/9.3/static/plpgsql-statements.html a simple equal sign was nevertheless accepted. –  Sep 06 '16 at 11:48
  • @a_horse_with_no_name but if both = and := are acceptable. Why did you say that := is prefered? Prefered for what reason? – ban Sep 06 '16 at 12:11
  • @ban: This related answer provides some background for `=` vs. `:=` in plpgsql: http://stackoverflow.com/a/22001209/939860 – Erwin Brandstetter Sep 07 '16 at 02:06
  • 1
    @ban - "=" is logical operator, ":=" is assign statement. Some languages that using "=" for assigning use different symbol for equivalence. PLpgSQL has some limits against origin ADA so this difference doesn't play big role, but better to be consistent with original language - the possibility to use "=" for assignment is bug, but it is too late to fix it. – Pavel Stehule Sep 08 '16 at 03:46