Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a nested function in PL/pgSQL?

I would like to create a function in PL/pgSQL with a couple of nested (or inner) functions within it. This way I can break the problem down into smaller pieces but not have my smaller pieces accessible outside of this function.

Is it possible to do this in PL/pgSQL? If so, how?

like image 385
Gregory Arenius Avatar asked Oct 11 '16 17:10

Gregory Arenius


People also ask

How do you call a function within a function in PostgreSQL?

The normal syntax to call another PL/pgSQL function from within PL/pgSQL is to either reference the function in a SQL SELECT statement, or during the assignment of a variable. For example: SELECT function_identifier ( arguments ); variable_identifier := function_identifier ( arguments );

Can we commit inside a function in PostgreSQL?

Basically, PostgreSQL version 11 allows users to perform autonomous transactions like COMMIT or ROLLBACK inside a procedural code that can be invoked using the CALL keyword.

What is Plpgsql function?

With PL/pgSQL you can group a block of computation and a series of SQL queries inside the database server, thus having the power of a procedural language and the ease of use of SQL. Also, with PL/pgSQL you can use all the data types, operators and functions of Greenplum Database SQL.

Can we use PL SQL in PostgreSQL?

PL/pgSQL comes with PostgreSQL by default. The user-defined functions and stored procedures developed in PL/pgSQL can be used like any built-in functions and stored procedures. PL/pgSQL inherits all user-defined types, functions, and operators.


2 Answers

Try it:

CREATE OR REPLACE FUNCTION outer() RETURNS void AS $outer$
DECLARE s text;
BEGIN
  CREATE OR REPLACE FUNCTION inner() RETURNS text AS $inner$
  BEGIN
    RETURN 'inner';
  END;
  $inner$ language plpgsql;

  SELECT inner() INTO s;
  RAISE NOTICE '%', s;

  DROP FUNCTION inner();
END;
$outer$ language plpgsql;

In postgres 9.5 SELECT outer(); outputs

 psql:/vagrant/f.sql:14: NOTICE:  inner

EDIT: if you don't drop the inner function at the end of the outer function it will remain visible to the rest of the database.

like image 88
apteryx Avatar answered Sep 20 '22 12:09

apteryx


Nested functions are not supported by PLpgSQL. The emulation has not any sense and it is nonproductive.

like image 24
Pavel Stehule Avatar answered Sep 21 '22 12:09

Pavel Stehule