/ ID: 766 Title: Postgres Stored Procedures with Input and Output Parameters SQL 766 Meta Description: This article explores the use of the Postgres Stored Procedure using input and output parameters with SQL. Code samples included. Meta Keywords: Postgres Stored Procedures Input Output Parameters SQL Author: orkb Template: Unstructured Tutorial Categories: PostgreSQL Tags: PostgreSQL, Stored Procedures, SQL, Python Status: Published /

Introduction

In this tutorial, we learn to create Postgres Stored Procedures, including use of input and output parameters, in the SQL we write. We'll include:

Prerequisites

What is a "Stored Procedure" and how does it work?

Some features of Stored Procedures:

  1. We can refer to SPs as a "named program" that is stored in the database.
  2. Error checked.
  3. Compiled object.
  4. Procedures may or may not use parameters (argument values).
  5. Default for Stored Procedures is to not return values. Most likely, you will be feeding your SP a value(s) but expecting no return value, unless there is an error.
  6. Execution:
  7. Explicit execution. EXECUTE command, along with specific SP name and optional parameters.
  8. Implicite execution using only SP name.
  9. Can not be executed or called from within a SELECT.
  10. You can call a procedure as often as you like.

Why?

Purposes:

How?

For the bulk of this article, we'll explore how to create a Stored Procedure (SP) specifically using PostgreSQL's structured query language "PL/pgSQL", which was developed by Oracle. Let's begin with the syntax.

Syntax

SQL CREATE OR REPLACE PROCEDURE [proc name]([optional:parameters here]) IS [or "AS"] DECLARE [optional] [optional declaration section] BEGIN [execution; your actual "program"] EXCEPTION [optional] [optional: in case of error; error handling] END;

About Parameters

In terms of input and output to and from our Postgres Procedure, there are three kind of parameters:

Use Case

Let's begin with a simple table (named "technology") in our PostgreSQL relational database system. We use this table to track various database and coding technologies used in our company.

code public.technology id_tech t_name t_category

Note: We are assuming the id/_tech field is an auto-incrementing keyed index.

| id_tech | t_name | t_category | |---------|------------|------------| | 0 | Oracle | RDB | | 1 | Mongo | NoSQL | | 2 | MySQL | RDB | | 3 | PostgreSQL | RDB | | 4 | Python | Language | | 5 | PHP | Language |

``` SQL CREATE OR REPLACE PROCEDURE ADD_USER ( P_t_name IN technology.t_name%TYPE, P_t_category IN technology.t_category%TYPE, P_t_msg_error OUT VARCHAR2 ) IS

DECLARE -- No variable declarations at this time.

BEGIN INSERT INTO technology ( t_name , t_category ) VALUES ( P_t_name , P_t_category COMMIT; EXCEPTION WHEN OTHERS THEN P_t_msg_error := SQLERRM; END ADD_USER; ```

Step by step explanation / analysis of the code above

OK, in case the above code is confusing for you, we'll take it from the top.

Calling our Stored Procedure

Because Python works so well with Postgres, we'll use this language for the example below.

``` PYTHON from flask import Flask # popular python library import psycopg2 # for database connection and dependent on Flask app = Flask(name) o_conn = psycopg2.connect(t_dsn) o_cursor = o_conn.cursor()

^ usually no need to repeat this ^

o_cursor.callproc('ADD_USER', ('Node.js','Language')) t_results = o_cursor.fetchone() o_cursor.close()

usually no need to repeat code below here

o_conn.close() ```

Here - if we assume the connection and cursor objects are not something we need to recreate and destroy over and over - we have three lines of code taking the place of Python, Java, PHP, Node, etc. code that builds the following:

SQL INSERT INTO technology ( t_name , t_category ) VALUES ( 'Node.js' , 'Language' COMMIT;

Note: The above SQL Statement doesn't include the TRY...COMMIT...EXCEPT block of error-checking code that may look like this:

PYTHON db_cursor.execute(s) try: db_conn.commit() except psycopg2.Error as e: t_message = "Database error: " + e + "/n SQL: " + s

Now, consider writing those INSERT INTO blocks of code over and over throughout your application but only changing what you send into those two fields? Do you see how much time and potential for typos you can save by using Stored Procedures instead? Of course here, we didn't make the number of inserted fields dynamic. Let's save that for a future article, eh?

Some tidbits

Conclusion

Here we learned why and how to create a Stored Procedure in Postgres to give us more efficiency, power, modularity, security, and ease. We also looked at how to call a Stored Procedure from Python.