In Oracle's PL/SQL I can create a session based global variable with the package definition. With Postgresql's PLpg/SQL, it doesn't seem possible since there are no packages, only independent procedures and functions.
Here is the syntax for PL/SQL to declare g_spool_key as a global...
CREATE OR REPLACE PACKAGE tox IS
g_spool_key spool.key%TYPE := NULL;
TYPE t_spool IS REF CURSOR RETURN spool%ROWTYPE;
PROCEDURE begin_spool;
PROCEDURE into_spool
(
in_txt IN spool.txt%TYPE
);
PROCEDURE reset_spool;
FUNCTION end_spool
RETURN t_spool;
FUNCTION timestamp
RETURN VARCHAR2;
END tox;
How would I implement a session based global variable with PLpg/SQL?
current_setting ( setting_name text [, missing_ok boolean ] ) → text. Returns the current value of the setting setting_name . If there is no such setting, current_setting throws an error unless missing_ok is supplied and is true (in which case NULL is returned). This function corresponds to the SQL command SHOW.
An assignment of a value to a PL/pgSQL variable is written as: variable { := | = } expression ; As explained previously, the expression in such a statement is evaluated by means of an SQL SELECT command sent to the main database engine.
A PostgreSQL session consists of the following cooperating processes (programs): A server process, which manages the database files, accepts connections to the database from client applications, and performs database actions on behalf of the clients. The database server program is called postgres .
PostgreSQL Stored Procedures support procedural operations, which are helpful while building powerful database apps — it increases their performance, productivity, and scalability. Like UDFs, stored procedures are a sequence of SQL statements available to apps that access an RDBMS.
Another option would be to create a temporary table, and use it to store all of your temporary variables
CREATE TEMPORARY TABLE tmp_vars(
name varchar(64),
value varchar(64),
PRIMARY KEY (name)
);
You could even create a stored procedure to manage everything, creating the table if it doesn't yet exist. One for retrieval and one for storage.
Unfortunately there are no global variables in PL/pgSQL, although you can find ones in other PL languages that come with PostgreSQL, specifically in PL/Perl, PL/Python and PL/Tcl
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With