DBMS Stored Function, Cursor & Trigger
DBMS Stored Function, Cursor & Trigger
com
• IN: It is the input parameter. It is used to insert the data from the procedure
into the table.
• OUT: It is the output parameter. It is used to return the value.
• INOUT: It represents both input and output parameters. As they can pass
and returns the value.
• VARIADIC: A PostgreSQL function can accept a variable number of
arguments with one condition have the same data type.
• The function must contain a return statement.
• RETURN clause specifies that data type you are going to return from the function.
The return_datatype can be a base, composite, or domain type, or can reference the
type of a table column.
• function-body contains the executable part.
• The AS keyword is used for creating a standalone function.
• plpgsql is the name of the language that the function is implemented in. Here, we
use this option for PostgreSQL, it Can be SQL, C, internal, or the name of a user
defined procedural language. For backward compatibility, the name can be enclosed
by single quotes.
Example:
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
Create or replace function hi_lo (IN a numeric, IN b numeric, IN c numeric, OUT hi numeric,
OUT lo numeric) AS’ BEGIN
hi := GREATEST(a,b,c); lo
:= LEAST(a,b,c);
END;
‘Language ‘plpgsql’;
Calling a function:
1. SELECT fuction_name(arguments);
2. Variable_identifier: = fuction_name(arguments);
e.g postgres=# SELECT hi_lo(10,20,30);
o/p : 30,10
We can also use the PERFORM keyword to call a function and ignore its
return data.
3. PERFORM fuction_name(arguments);
Dropping a function
drop function [if exists] function_name(argument_list)
[cascade | restrict]
Type: The data type(s) of the function’s arguments.
CASCADE: Automatically drop objects that depend on the function (such as operators or
triggers).
RESTRICT: Refuse to drop the function if any objects depend on it.
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
Functions should contain at least one Stored procedure neither contain any
parameter and should return value. parameter nor return any value.
Functions are created with the CREATE Procedures are created with the
FUNCTION command. CREATE PROCEDURE
We cannot call stored procedures We can call functions from stored
from functions. procedures.
Functions can have only input Procedures can have input or output
parameters for it. parameters.
Transactions are not allowed with Transactions can be executed from
functions. stored procedure also it can use
commit and rollback inside procedure.
Syntax:
Or
RAISE level format;
Following the RAISE statement is the level option that specifies the error severity.
PostgreSQL provides the following levels:
• DEBUG
• LOG
• NOTICE
• INFO
• WARNING
• EXCEPTION
The format is a string that specifies the message. The format uses percentage ( %)
placeholders that will be substituted by the next arguments. The number of
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
cnt INTEGER = 1;
BEGIN
cnt = cnt + 1;
RAISE NOTICE ''Variable an integer was changed.'';
RAISE NOTICE ''Variable an integer’s value is now %.'‘, cnt;
RAISE EXCEPTION ''Variable % changed. Transaction aborted. ‘cnt;
RETURN 1;
END;
' LANGUAGE 'plpgsql';
Raising Errors:
To raise errors, you use the EXCEPTION level after the RAISE statement. Note that
the RAISE statement uses the EXCEPTION level by default. Besides raising an error,
you can add more detailed information by using the following clause with the
RAISE statement:
USING option = expression
The options can be any one of the below:
• MESSAGE: set error message text
• HINT: provide the hint message so that the root cause of the error is easier to be
discovered.
• DETAIL: give detailed information about the error.
• ERRCODE: identify the error code, which can be either by condition name or
directly five-character SQLSTATE code.
Example 1: DO
$$
DECLARE
email varchar (255) := 'raju@geeksforgeeks.org';
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
BEGIN
-- check email for duplicate
-- ...
-- report duplicate email
RAISE EXCEPTION 'Duplicate email: %', email
USING HINT = 'Check the email again';
END $$;
Cursors:
A Cursor in PostgreSQL is used to process large tables. Suppose if a table has 10
million or billion rows. While performing a SELECT operation on the table it will
take some time to process the result and most likely give an “out of memory”
error and the program will be terminated.
A Cursor can only be declared inside a transaction. The cursor does not
calculate the data but only prepares the query so that your data can be created
when FETCH is called. In the end, simply commit the transaction.
Cursor can be two types.
1. Implicit cursors are declared and managed by pl/pgsql for all DML and
PL/pgsql select statement
2. Explicit cursors are declared and managed by the programmer.
Explicit cursors operations are as follows.
1.First, declare a cursor.
2.Next, open the cursor.
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
Syntax:
DECLARE
[cursor name] CURSOR FOR [query]
• Use DECLARE to declare a cursor
• [cursor name] – Give any name to the cursor
• [query] – Give a query to the cursor
3.Fetching Rows:
After declaring a cursor, we can get the data using FETCH. The FETCH gets the next
row(s) from the cursor. If no row found, then it returns NULL.
Syntax:
FETCH [direction (rows)] FROM [cursor_name];
where direction can be empty, number of rows you want or one of the
following valid directions for the cursor:
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
NEXT
PRIOR
FIRST
LAST
ABSOLUTE count
RELATIVE count
count ALL
FORWARD BACKWARD
4.closing cursors
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
Trigger
A PostgreSQL trigger is a function invoked automatically whenever an event
associated with a table occurs. An event could be any of the following:
INSERT, UPDATE, DELETE or TRUNCATE.
The differences between the two kinds are how many times the trigger is
invoked and at what time. For example, if you issue an UPDATE statement that
affects 20 rows, the row-level trigger will be invoked 20 times, while the
statement level trigger will be invoked 1 time.
You can specify whether the trigger is invoked before or after an event. If the
trigger is invoked before an event, it can skip the operation for the current row
or even change the row being updated or inserted. In case the trigger is
invoked after the event, all changes are available to the trigger.
Create Trigger:
[
-- Trigger logic
Execute PROCEDURE trigger function
];
The trigger-name is the name of the trigger.
The BEFORE, AFTER and INSTEAD OF are keywords that determine
when the trigger will be invoked.
The event-name is the name of the event that will cause the trigger
to be invoked. This can be INSERT, UPDATE, DELETE, etc.
List Trigger
All triggers that you create in PostgreSQL are stored in the pg_trigger table. To see
the list of triggers that you have on the database, query the table by running the
SELECT command as shown below:
Drop Trigger
In PostgreSQL, the DROP TRIGGER statement is used to drop a trigger from a table.
Syntax:
DROP TRIGGER [IF EXISTS] trigger_name
ON table_name [ CASCADE | RESTRICT];
The table-name denotes the name of the table from which the trigger is to be
deleted.
The IF EXISTS clause attempts to delete a trigger that exists. If you attempt to
delete a trigger that does not exist without using the IF EXISTS clause, you will get
an error.
The CASCADE option will help you to drop all objects that depend on the trigger
automatically.
Copyright © austinmakasare22@gmail.com
Copyright © austinmakasare22@gmail.com
If you use the RESTRICT option, the trigger will not be deleted if objects are
depending on it.
Advantage of Trigger
Disadvantage of Trigger:
1.Triggers are invoked and executed invisible from the client applications
therefore it is difficult to figure out what happen in the database layer
Copyright © austinmakasare22@gmail.com