Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Session based global variable in Postgresql stored procedure?

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?

like image 633
dacracot Avatar asked Jan 05 '09 21:01

dacracot


People also ask

What is Current_setting in PostgreSQL?

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.

How do I assign a variable in Plpgsql?

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.

What is a PostgreSQL session?

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 .

Can we use stored procedure in PostgreSQL?

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.


2 Answers

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.

like image 108
Ben Avatar answered Jan 03 '23 16:01

Ben


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

like image 31
porkbird Avatar answered Jan 03 '23 17:01

porkbird