K. J. Somaiya College of Engineering, Mumbai-77
K. J. Somaiya College of Engineering, Mumbai-77
Grade: AA / AB / BB / BC / CC / CD /DD
1. Dr. P.S. Deshpande, SQL and PL/SQL for Oracle 10g.Black book, Dreamtech Press
2. www.db-book.com
3. Korth, Slberchatz, Sudarshan : “Database Systems Concept”, 5th Edition , McGraw
Hill
4. Elmasri and Navathe,”Fundamentals of database Systems”, 4th Edition,PEARSON
Education.
Theory
A stored procedure provides an important layer of security between the user interface
and the database. It supports security through data access controls because end users may
enter or change data, but do not write procedures. A stored procedure preserves data
integrity because information is entered in a consistent manner. It improves productivity
because statements in a stored procedure only must be written once.
Use of stored procedures can reduce network traffic between clients and servers, because
the commands are executed as a single batch of code. This means only the call to execute
the procedure is sent over a network, instead of every single line of code being sent
individually.
Syntax:
CREATE [ OR REPLACE ] PROCEDURE
name ( [ [ argmode ] [ argname ] argtype [ { DEFAULT | = }
default_expr ] [, ...] ] )
{ LANGUAGE lang_name
| TRANSFORM { FOR TYPE type_name } [, ... ]
| [ EXTERNAL ] SECURITY INVOKER | [ EXTERNAL ] SECURITY
DEFINER
| SET configuration_parameter { TO value | = value | FROM
CURRENT }
| AS 'definition'
| AS 'obj_file', 'link_symbol'
} ...
Parameters
Name: The name (optionally schema-qualified) of the procedure to create.
Argmode: The mode of an argument: IN, INOUT, or VARIADIC. If omitted, the default
is IN. (OUT arguments are currently not supported for procedures. Use INOUT instead.)
Argname: The name of an argument.
Argtype: The data type(s) of the procedure's arguments (optionally schema-qualified),
if any. The argument types can be base, composite, or domain types, or can reference the
type of a table column.
Depending on the implementation language it might also be allowed to specify “pseudo-
types” such as cstring. Pseudo-types indicate that the actual argument type is either
incompletely specified, or outside the set of ordinary SQL data types.
If a SET clause is attached to a procedure, then the effects of a SET LOCAL command
executed inside the procedure for the same variable are restricted to the procedure: the
When repeated CREATE PROCEDURE calls refer to the same object file, the file is only
loaded once per session. To unload and reload the file (perhaps during development),
start a new session.
Example:
We will use the following accounts table for the demonstration:
The following example creates stored procedure named transfer that transfer specific
amount of money from one account to another.
CREATE OR REPLACE PROCEDURE transfer(INT, INT, DEC)
LANGUAGE plpgsql
AS $$
BEGIN
-- subtracting the amount from the sender's account
UPDATE accounts
SET balance = balance - $3
WHERE id = $1;
COMMIT;
END;
$$;
CALL stored_procedure_name(parameter_list);
CALL transfer(1,2,1000);
Cursors
Rather than executing a whole query at once, it is possible to set up a cursor that
encapsulates the query, and then read the query result a few rows at a time. One reason
for doing this is to avoid memory overrun when the result contains a large number of
rows. (However, PL/pgSQL users do not normally need to worry about that, since FOR
loops automatically use a cursor internally to avoid memory problems.) A more
interesting usage is to return a reference to a cursor that a function has created, allowing
the caller to read the rows. This provides an efficient way to return large row sets from
functions.
Before a cursor can be used to retrieve rows, it must be opened. (This is the equivalent
action to the SQL command DECLARE CURSOR.) PL/pgSQL has three forms of the
OPEN statement, two of which use unbound cursor variables while the third uses a bound
cursor variable.
OPEN FOR query
Syntax: OPEN unbound_cursorvar [ [ NO ] SCROLL ] FOR query;
example:
Using Cursors
FETCH
Synatx: FETCH [ direction { FROM | IN } ] cursor INTO target;
Examples:
MOVE curs1;
MOVE LAST FROM curs3;
MOVE RELATIVE -2 FROM curs4;
MOVE FORWARD 2 FROM curs4;
UPDATE/DELETE WHERE CURRENT OF
UPDATE table SET ... WHERE CURRENT OF cursor;
DELETE FROM table WHERE CURRENT OF cursor;
When a cursor is positioned on a table row, that row can be updated or deleted using the
cursor to identify the row. There are restrictions on what the cursor's query can be (in
particular, no grouping) and it's best to use FOR UPDATE in the cursor. For more
information see the DECLARE reference page.
An example:
UPDATE foo SET dataval = myval WHERE CURRENT OF curs1;
CLOSE
CLOSE cursor;
CLOSE closes the portal underlying an open cursor. This can be used to release resources
earlier than end of transaction, or to free up the cursor variable to be opened again.
An example:
CLOSE curs1;
SELECT cip.totalRecords();
Output:
Cursors:
1. User-defined cursors
Code:
REATE OR REPLACE FUNCTION cip.function_1(refcursor) RETURNS refcursor AS
$$
BEGIN
OPEN $1 FOR SELECT * FROM cip.college;
RETURN $1;
END;
$$ LANGUAGE plpgsql;
SELECT cip.functio('myowncursorname');
fetch all from "myowncursorname";
output:
2. Inbuilt cursors
Code:
CREATE OR REPLACE FUNCTION cip.function_1() RETURNS refcursor AS $$
DECLARE
ref_cursor REFCURSOR := 'mycursor';
BEGIN
OPEN ref_cursor FOR SELECT * FROM cip.college;
RETURN (ref_cursor);
END;
$$ LANGUAGE plpgsql
SELECT cip.function_1();
FETCH 3from mycursor;
Output:
Procedure:
CREATE or replace procedure cip.ratChan(varchar,int)
LANGUAGE plpgsql
AS $$
BEGIN
UPDATE cip.college
SET rating = $2
WHERE col_id =$1;
COMMIT;
END;
$$;
CALL cip.ratChan('112301',2);
Output:
Conclusion:
Ans: Data stored in stored procedures can be retrieved much faster than the data stored
in SQL database. Data can be precompiled and stored in Stored procedures. This
reduces the time gap between query and compiling as the data has been precompiled
and stored in the procedure.
3. Visit following virtual lab link, read theory and procedure provided and
solve pretest and post test questions. Support your answers with
screenshots.
Link:
http://vlabs.iitb.ac.in/vlabs-dev/labs/dblab/labs/exp3/index.php