Stored Procedure used in PosgreSQL
description
Transcript of Stored Procedure used in PosgreSQL
Professor: Dr. Shu-Ching ChenTA: Hsin-Yu Ha
Stored Procedure used in PosgreSQL
What are stored proceduresA subroutine available to applications that
access a relational database system.PL/pgSQL : A loadable procedural language.
Creates functions and trigger proceduresAdds control structuresPerforms complex computationInherits all user-defined types, functionsCan be defined to be trusted by the serverEasy to use
Why do we need stored procedure
One Query Wait, receive, process/computeDatabase
ServerIntern
et
Reduce roundtrips across the networkCan make security easier to manageAre precompiled
Structure of PL/pgSQL
Declarations (1)Declaring PL/pgSQL variable
Declarations (2)Declaring PL/pgSQL variable and assigning
values
Declarations (3)Declaring Function Parameters(1) directly give a name to the parameter in the command
(2) name ALIAS FOR $n;
Declarations (4)Directly using argument variables
Declarations (5)Attributes
%TYPE attribute
Declarations (6)Attributes
%ROWTYPE attribute
Comment syntax Single-line comments
Block comments
Basic Statements (1)Assignment
Executing a Command with NO RESULT – PERFORM
Basic Statements (2)Executing a Command with a Single-row
result
Basic Statements (3)Example
Basic Statements (4)
Basic Statements (5)FOUND – Boolean variable
Control Structures(1)RETURN expression
Control Structures(2)IF statements
IF … THENIF … THEN … ELSEIF … THEN … ELSIF … THEN … ELSE
Control Structures(3)CASE statements
CASE … WHEN … THEN … ELSE … END CASECASE WHEN … THEN … ELSE … END CASE
Control Structures(4)LOOP
EXIT
Control Structures(5)CONTINUE
WHILE
Control Structures(6)FOR (Integer Variant)
Control Structures(7)FOR (Looping through query results)
Control Structures(8)Trapping Errors
http://www.postgresql.org/docs/9.1/static/errcodes-appendix.html#ERRCODES-TABLE
Cursors (1)Declaring Cursor Variables
OPEN FOR query
Cursors (2)Using Cursors
FETCH
MOVE
NEXT PRIORFIRSTLASTABSOLUTE countRELATIVE countFORWARDBACKWORD
Cursors (3)Using Cursors
CLOSE
Returning Cursor
Cursors (4)Looping Through a Cursor’s Result
Errors and MessagesRAISE
Example
ReferencePostgreSQL Manuals PostgreSQL 9.1
http://www.postgresql.org/docs/9.1/static/index.html
Practical PostgreSQLhttp://www.faqs.org/docs/ppbook/c19610.htm
Stored Procedure in PgAdmin
1
2 3
Stored Procedure in PgAdmin