0

I've a PostgreSQL function that returns a string. I want to use this function into another one but I obtain an error.

These are the sample functions, with get_some_string that returns text, and use_the_string where I want to call the previous one and store the result in a variable:

CREATE OR REPLACE FUNCTION public.get_some_string()

RETURNS text AS
$func$
DECLARE

BEGIN

  return 'mystring';

END
$func$ LANGUAGE plpgsql VOLATILE;

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := select public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;

If I run this query I obtain the error:

ERROR:  syntax error at or near "select"
LINE 24:   mytext := select public.get_some_string();

What I'm doing wrong? How can I use the return value of the first function into the second one?

1
  • mytext := (select public.get_some_string()); Commented Nov 17, 2017 at 11:56

3 Answers 3

3

You don't need a select:

CREATE OR REPLACE FUNCTION public.use_the_string()

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  mytext := public.get_some_string();

END
$func$ LANGUAGE plpgsql VOLATILE;
Sign up to request clarification or add additional context in comments.

Comments

2

The second one must be:

RETURNS boolean AS
$func$
DECLARE

  mytext text;

BEGIN

  select public.get_some_string() into mytext;

END
$func$ LANGUAGE plpgsql VOLATILE;

or

mytext := (select public.get_some_string());

or

mytext := public.get_some_string();

Comments

1

Note to other answers: select is implicitly added in plpgsql context. Example:

do $$
declare
  v text[];
begin
  v := array_agg(datname) from pg_database;
  raise info 'List of databases: %', v;
end $$;

So when you call mytext := select public.get_some_string(); it is transformed to select select public.get_some_string(); internally.

Thats why parenthesesis mytext := (select public.get_some_string()); could be the solution: select (select public.get_some_string()); is the acceptable statement.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.