Presentation is loading. Please wait.

Presentation is loading. Please wait.

Stored Procedure used in PosgreSQL

Similar presentations


Presentation on theme: "Stored Procedure used in PosgreSQL"— Presentation transcript:

1 Stored Procedure used in PosgreSQL
Professor: Dr. Shu-Ching Chen TA: Yimin Yang

2 What are stored procedure
A subroutine available to applications that access a relational database system. PL/pgSQL : A loadable procedural language. Creates functions and trigger procedures Adds control structures Performs complex computation Inherits all user-defined types, functions Can be defined to be trusted by the server Easy to use PL/pgSQL is a loadable procedural language for the PostgreSQL database system. The design goals of PL/pgSQL were to create a loadable procedural language that can be used to create functions and trigger procedures, adds control structures to the SQL language, can perform complex computations, inherits all user-defined types, functions, and operators, can be defined to be trusted by the server, is easy to use. A stored procedure is a subroutine available to applications that access a relational database system. A stored procedure (sometimes called a proc, sproc, StoPro, StoredProc, orSP) is actually stored in the database data dictionary.

3 Why do we need stored procedure
Reduce roundtrips across the network Can make security easier to manage Are precompiled One Query Wait, receive, process/compute Database Server Internet Reduce roundtrips across the network - Stored procedures take zero or more input parameters, do something, and return a result, much like a function in any language. By “black boxing” that functionality on the database server, we avoid the need to move large datasets across the wire to the application server for processing. This can decrease network utilization and application latency. Can make security easier to manage - While views can help simplify the permissions needed for complex queries, stored procedures make it even easier. Instead of giving a user/application the correct rights to specific tables (or columns), a person only needs execution rights to the stored procedure. Are precompiled - Stored procedures are stored in a precomplied state on the server, meaning that the query optimizer doesn’t have to recalculate the most efficient execution path each time the query is run. This reduces server overhead and can speed things up a bit.

4 Structure of PL/pgSQL PL/pgSQL code is organized in blocks of code. This method of organization is known as block structured code. Code blocks are entered within a SQL CREATE FUNCTION call that creates the PL/pgSQL function in the PostgreSQL database. This CREATE FUNCTION command names the new function, states its argument types, and states the return type. The function's main code block then starts with a declaration section. All variables are declared and optionally initialized to a default value in the declaration section of a code block. A variable declaration specifies the variable's name and type. The declaration section is denoted by the DECLARE keyword. Each variable declaration is ended with a semicolon. After declaring variables, the main body of the code block is started with the BEGIN keyword. The code block's statements should appear after the BEGIN keyword. The END keyword designates the end of the code block. The main block of a PL/pgSQL function should return a value of its specified return type and end any sub-blocks (code blocks started within another code block) before its END keyword is reached.

5 Declarations (1) Declaring PL/pgSQL variable

6 Declarations (2) Declaring PL/pgSQL variable and assigning values
The NOT NULL keywords indicate that a variable cannot be set as NULL. The DEFAULT keyword allows you to provide a default value for a variable. Alternatively, you can use the := operator without specifying the DEFAULT keyword, to the same effect.

7 Declarations (3) Declaring Function Parameters
(1) directly give a name to the parameter in the command (2) name ALIAS FOR $n;

8 Declarations (4) Directly using argument variables

9 Declarations (5) Attributes %TYPE attribute

10 Declarations (6) Attributes %ROWTYPE attribute

11 Comment syntax Single-line comments Block comments
Single line comments begin with two dashes (- -) and have no end-character. The parser interprets all characters on the same line after the two dashes as part of the comment. The second type of comment is the multiline or block comment, which should be familiar to most anyone who has worked with programming languages before. Block comments begin with the forward slash and asterisk characters (/*) and end with the asterisk and forward slash characters (*/). Block comments can span multiple lines, and any text between the opening /* and closing */ is considered a comment. Example 11-7 shows the correct usage of a block comment.

12 Basic Statements (1) Assignment
Executing a Command with NO RESULT – PERFORM

13 Basic Statements (2) Executing a Command with a Single-row result
If the STRICT option is specified, the query must return exactly one row or a run-time error will be reported, either NO_DATA_FOUND (no rows) or TOO_MANY_ROWS (more than one row). You can use an exception block if you wish to catch the error, for example: where target can be a record variable, a row variable, or a comma-separated list of simple variables and record/row fields If STRICT is not specified in the INTO clause, then target will be set to the first row returned by the query, or to nulls if the query returned no rows. (Note that "the first row" is not well-defined unless you've used ORDER BY.) Any result rows after the first row are discarded.

14 Basic Statements (3) Example

15 Basic Statements (4)

16 Basic Statements (5) FOUND – Boolean variable
Use the special FOUND Boolean variable directly after a SELECT INTO statement to check whether or not the statement successfully inserted a value into the specified variable

17 Control Structures(1) RETURN expression

18 Control Structures(2) IF statements IF … THEN IF … THEN … ELSE
IF … THEN … ELSIF … THEN … ELSE

19 Control Structures(3) CASE statements
CASE … WHEN … THEN … ELSE … END CASE CASE WHEN … THEN … ELSE … END CASE

20 Control Structures(4) LOOP EXIT
LOOP defines an unconditional loop that is repeated indefinitely until terminated by an EXIT or RETURN statement. The optional label can be used by EXIT and CONTINUE statements within nested loops to specify which loop those statements refer to. If no label is given, the innermost loop is terminated and the statement following END LOOP is executed next. If label is given, it must be the label of the current or some outer level of nested loop or block. Then the named loop or block is terminated and control continues with the statement after the loop's/block's corresponding END. If WHEN is specified, the loop exit occurs only if boolean-expression is true. Otherwise, control passes to the statement after EXIT. EXIT can be used with all types of loops; it is not limited to use with unconditional loops. When used with a BEGIN block, EXIT passes control to the next statement after the end of the block. Note that a label must be used for this purpose; an unlabelled EXIT is never considered to match a BEGIN block.

21 Control Structures(5) CONTINUE WHILE

22 Control Structures(6) FOR (Integer Variant)

23 Control Structures(7) FOR (Looping through query results)

24 Control Structures(8) Trapping Errors
appendix.html#ERRCODES-TABLE If no error occurs, this form of block simply executes all the statements, and then control passes to the next statement afterEND. But if an error occurs within the statements, further processing of the statements is abandoned, and control passes to the EXCEPTION list. The list is searched for the first condition matching the error that occurred. If a match is found, the corresponding handler_statements are executed, and then control passes to the next statement after END. If no match is found, the error propagates out as though the EXCEPTION clause were not there at all: the error can be caught by an enclosing block with EXCEPTION, or if there is none it aborts processing of the function.

25 Cursors (1) Declaring Cursor Variables OPEN FOR query
This provides an efficient way to return large row sets from functions. 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 create a cursor variable is just to declare it as a variable of type refcursor All three of these variables have the data type refcursor, but the first can be used with any query, while the second has a fully specified query already bound to it, and the last has a parameterized query bound to it.

26 Cursors (2) Using Cursors FETCH MOVE NEXT PRIOR FIRST LAST
ABSOLUTE count RELATIVE count FORWARD BACKWORD Using Cursors FETCH MOVE NEXT Fetch the next row. This is the default if direction is omitted. PRIOR Fetch the prior row. FIRST Fetch the first row of the query (same as ABSOLUTE 1). LAST Fetch the last row of the query (same as ABSOLUTE -1). ABSOLUTE count Fetch the count'th row of the query, or the abs(count)'th row from the end if count is negative. Position before first row or after last row if count is out of range; in particular, ABSOLUTE 0 positions before the first row. RELATIVE count Fetch the count'th succeeding row, or the abs(count)'th prior row if count is negative. RELATIVE 0 re-fetches the current row, if any.

27 Cursors (3) Using Cursors CLOSE Returning 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

28 Cursors (4) Looping Through a Cursor’s Result
The cursor variable must have been bound to some query when it was declared, and it cannot be open already. The FOR statement automatically opens the cursor, and it closes the cursor again when the loop exits. A list of actual argument value expressions must appear if and only if the cursor was declared to take arguments. These values will be substituted in the query, in just the same way as during an OPEN. The variable recordvar is automatically defined as type record and exists only inside the loop (any existing definition of the variable name is ignored within the loop). Each row returned by the cursor is successively assigned to this record variable and the loop body is executed.

29 Errors and Messages RAISE Example

30 Reference PostgreSQL Manuals PostgreSQL 9.1 Practical PostgreSQL
Practical PostgreSQL COST in stored procedures: A positive number giving the estimated execution cost for the function, in units of cpu_operator_cost. If the function returns a set, this is the cost per returned row. If the cost is not specified, 1 unit is assumed for C-language and internal functions, and 100 units for functions in all other languages. Larger values cause the planner to try to avoid evaluating the function more often than necessary. "

31 Stored Procedure in PgAdmin
2 3 1

32 Stored Procedure in PgAdmin


Download ppt "Stored Procedure used in PosgreSQL"

Similar presentations


Ads by Google