How would I return the return value of a function from within a function (eg. foo()
calls bar()
)?
create or replace function bar ()
returns text
as $$
begin
select md5(random()::text);
end
$$ language 'plpgsql';
create or replace function foo ()
returns text
as $$
begin
return select bar ();
end
$$ language 'plpgsql';
I keep getting errors like query has no destination for result data
You need to provide something to accept the output of the query:
CREATE OR REPLACE FUNCTION public.bar()
RETURNS text
LANGUAGE plpgsql
AS $function$
declare
md5_val text;
begin
select into md5_val md5(random()::text);
return md5_val;
end
$function$
;
create or replace function foo ()
returns text
as $$
declare
md5_val2 text;
begin
select into md5_val2 bar();
return md5_val2;
end
$$ language 'plpgsql';
select * from foo();
foo
----------------------------------
ac6a4910fac3472d226dc54bb147336e
See:
https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-SQL-ONEROW
Both of your functions are some impermissible mixture of 'plpgsql' language and 'sql' language functions. Also, it isn't about calling one from the other, bar() is broken even if you just call it directly, and once fixed then foo() is broken independently of bar() being broken.
Nothing here needs to be in plpgsql, so the simplest repair is just to turn them into 'sql' language functions.
create or replace function bar ()
returns text
as $$
select md5(random()::text);
$$ language 'sql';
create or replace function foo ()
returns text
as $$
select bar();
$$ language 'sql';
If you want them to be plpgsql, then in first case you need to return
something, it doesn't just automatically return the result of the last query like SQL language functions do. And in the second one, "return select" is not valid. You could select into a scratch variable and then return that scratch variable, but it easier just to change the "select" to "return" in the first, and remove the wayward "select" in the second.
create or replace function bar ()
returns text
as $$
begin
return md5(random()::text);
end
$$ language 'plpgsql';
create or replace function foo ()
returns text
as $$
begin
return bar();
end
$$ language 'plpgsql';
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.