Download presentation
Presentation is loading. Please wait.
1
PL/SQL
2
introduction SQL does not have procedural capabilities.
SQL does not provide the programming techniques of condition checking, looping and branching that is required for data before permanent storage. SQL statements are passed to the oracle engine one at time, each time an SQL statement will be executed, so each time need to call oracle engine. This will increase traffic on the network, so it reduce speed of data processing specially in client- server application.
3
Introduction If any error occur in SQL statement, the oracle engine will display its own error message, SQL has no facility to provide user friendly error. PL/SQL is superset of SQL. Procedural language extension SQL
4
Advantages of pl/sql PL/SQL provide facilities of conditional checking, branching and looping. PL/SQL dealing with error and facilities displaying user-friendly messages, when error occurred. PL/SQL allows declaration of variable, variable, we can use in intermediate result of query processing, or calculate values and insert them into table. PL/SQL can be used any where, either in SQL statements or PL/SQL blocks.
5
advantages Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.
6
PL/SQL Blocks PL/SQL code is built of Blocks, with a unique structure.
There are two types of blocks in PL/SQL: Anonymous Blocks: have no name (like scripts) can be written and executed immediately in SQLPLUS can be used in a trigger 2. Named Blocks: Procedures Functions
7
Anonymous Block Structure:
DECLARE (optional) /* Here you declare the variables you will use in this block */ BEGIN (mandatory) /* Here you define the executable statements (what the block DOES!)*/ EXCEPTION (optional) /* Here you define the actions that take place if an exception is thrown during the run of this block */ END; (mandatory) / A correct completion of a block will generate the following message: PL/SQL procedure successfully completed Always put a new line with only a / at the end of a block! (This tells Oracle to run the block)
8
Declare section Code blocks start with a declaration section.
Declaration of memory variables, constants, cursor etc. Once declared, they can be used in SQL statements for data manipulation.
9
Begin section It consists of SQL executable statements as well as PL/SQL statements. Which describe processes that have to be applied to table data. Data manipulation, retrieval, looping and branching constructs are specified in this section.
10
The exception section This section deals with handling of errors that occur during execution of the data manipulation statements. Errors can occur due to syntax, logic and/or validation rule.
11
The character set The basic character set includes the following:
Upper case Alphabets { A – Z } Lower case alphabets { a- z } Number { 0 – 9 } Symbols ( ), * etc. Words used in PL/SQL block are called Lexical Units. We can insert free blank spaces in lexical unit there will be no effect on PL/SQL block.
12
Literals Numeric literal It can be either integer of floats.
If float is being represented, then the integer part must be separated from the float part by a period. Example 25, 6.34 etc
13
String literal These are represented by one or more legal characters and must be enclosed with in single quotes. Example ‘hello there’
14
Character literal These are string literal consisting of single characters. Example: ‘*’, ‘A’.
15
Pl/sql data types The default data type can be use in PL/SQL. NUMBER
CHAR DATE VARCHAR BOOLEAN
16
VARIABLES Variables in PL/SQL block are named variables.
Variable must begin with character and can be followed by a maximum 29 other characters. Reserve words can not be used. Variables separated from each other by punctuation mark. White space can not be used in variable name.
17
Assigning values to variable
The assigning of a value to a variable can be done in two ways: Using the assignment operator : = (i.e. a colon followed by an equal to sign). Selecting or fetching table data values into variables.
18
Constant What is constant?
Declaring a constant is similar to declaring a variable except that the keyword CONSTANT must be added to the variable name and a value assigned immediately.
19
Displaying user message
To display message, the SERVEROUTPUT should be set ON. SYNTAX: - SET SERVEROUTPUT [ON/OFF]; DBMS_OUTPUT is a package that includes a number of procedure and function that we can use. PUT_LINE puts a piece information in the package buffer followed by an end-of-line marker.
20
SIMPLE EXAMPLE
21
Control structure Conditional control Iterative control
Sequential control.
22
Conditional control If <cond> then if <cond2>
Nested conditions: If <cond> then <command> elsif <cond2> then <command2> else <command3> end if; If <cond> then if <cond2> <command1> end if; else <command2>
23
Example of if statement
24
Iterative control SIMPLE LOOP SYNTAX: LOOP
<sequences of statements> END LOOP
25
Example of simple loop
26
WHILE <CONDITION> LOOP <ACTION> END LOOP;
While loop Syntax WHILE <CONDITION> LOOP <ACTION> END LOOP;
27
EXAMPLE OF WHILE LOOP
28
FOR LOOP SYNTAX: FOR variable IN [REVERSE] start….end LOOP
<ACTION> END LOOP;
29
EXAMPLE OF FOR LOOP
30
SIMPLE EXAMPLE
31
SIMPLE EXAMPLE-2
32
CURSOR The oracle engine uses a work area for its internal processing area in order to execute an SQL statement. This work area is private SQL’S operation and is called a cursor. The data that is stored in the cursor is called the ACTIVE DATA SET.
33
TYPES OF CURSOR Implicit cursor: - if oracle engine opened a cursor for its internal processing, it is known as implicit cursor. Explicit cursor: - A cursor can also be opened for processing data through PL/SQL block. Such a user defined cursor is known as an Explicit cursor.
34
General Cursor Attributes
Obtain status information about a cursor. Attribute Type Description %ISOPEN Boolean Evaluates to TRUE if the cursor is open. %NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row. %FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so far. Explicit Cursor Attributes As with implicit cursors, there are four attributes for obtaining status information about a cursor. When appended to the cursor or cursor variable, these attributes return useful information about the execution of a data manipulation statement. Note: Do not reference cursor attributes directly in a SQL statement.
35
Example of cursor
36
Another example
37
Explicit cursor The only means of generating an explicit cursor is for the cursor to be named in the DECLARE section of the PL/SQL Block. The advantages of declaring an explicit cursor over the indirect implicit cursor are that the explicit cursor gives more programmatic control to the programmer. Implicit cursors are less efficient than explicit cursors and thus it is harder to trap data errors.
38
Explicit cursor The process of working with an explicit cursor consists of the following steps: DECLARING the cursor. This initializes the cursor into memory. OPENING the cursor. The previously declared cursor can now be opened; memory is allotted. FETCHING the cursor. The previously declared and opened cursor can now retrieve data; this is the process of fetching the cursor. CLOSING the cursor. The previously declared, opened, and fetched cursor must now be closed to release memory allocation.
39
DECLARING A CURSOR Declaring a cursor defines the name of the cursor and associates it with a SELECT statement. The first step is to Declare the Cursor with the following syntax: CURSOR c_cursor_name IS select statement Cursor names follow the same rules of scope and visibility that apply to the PL/SQL identifiers. Because the name of the cursor is a PL/SQL identifier, it must be declared before it is referenced. Any valid select statement can be used to define a cursor, including joins and statements with the UNION or MINUS clause.
40
Opening cursor The next step in controlling an explicit cursor is to open it. When the Open cursor statement is processed, the following four actions will take place automatically: The variables (including bind variables) in the WHERE clause are examined. Based on the values of the variables, the active set is determined and the PL/SQL engine executes the query for that cursor. Variables are examined at cursor open time only. The PL/SQL engine identifies the active set of data—the rows from all involved tables that meet the WHERE clause criteria. The active set pointer is set to the first row.
41
OPENING A CURSOR The syntax for opening a cursor is: OPEN cursor_name;
42
FETCHING ROWS IN A CURSOR
After the cursor has been declared and opened, you can then retrieve data from the cursor. The process of getting the data from the cursor is referred to as fetching the cursor. There are two methods of fetching a cursor, done with the following command: FETCH cursor_name INTO PL/SQL variables; or FETCH cursor_name INTO PL/SQL record;
43
Fetching rows in a cursor
Syntax FETCH cursorName into variable1, variable2….
44
Explicit cursor example
45
Stored Procedure /Function
A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a specific task. To make a procedure of function, we can passed parameters before execution.
46
Procedure and function
Procedure and function are made up of: A declarative part An executable part An optional exception-handling part
47
Procedure and function
Procedure and Function are stored in Oracle Database. They can be invoked or call by any PL/SQL block. Before procedure or function is stored, the oracle engine parse and compiles the procedure or function.
48
How does the oracle engine create a stored procedure/function?
Few steps are performed by the oracle engine while creating a procedure. Compiles the procedure or function Stores the procedure of function in the database. If oracle engine compiles the PL/SQL block, if any error occurs during the compilation of procedure or function , an invalid procedure of function gets created. The oracle engine display a message after the creation that the procedure or function was created with compilation errors.
49
The compilation process does not display error message.
If we want to see error message, error can be viewed using SELECT statement. SELECT * FROM USER_ERRORS; When function or procedure invoked, the oracle engine load the compiled procedure or function in a memory area called the SYSTEM GLOBAL AREA (SGA).
50
EXECUTE PROCEDURE/FUNCTION
Oracle engine performs the following steps to execute a procedure or function Verify user access Verifies procedure of function validity. Executes the procedure or function.
51
Advantage of procedure/function
Security Procedure and Function can help to enforce data security Giving permission to users to access Procedure or Function. Performance Amount of information sent over a network is less. No compilation step is required to execute the code.
52
Memory Allocation The amount of memory used reduced because function and procedure can shared memory. Only one copy of procedure or function need to be load or used by different users. Productivity Redundant coding can be avoided, increased productivity. Integrity. Procedure or function need to tested only once that it give accurate result each time.
53
Procedure versus function
Function must return value. Function can return only one value, but, by defining multiple OUT parameters in a procedure, multiple values can be passed to the caller.
54
Creating stored procedure
Syntax CREATE OR REPLACE PROCEDURE [SCHEMA] <procedureName> (<arguments> { IN, OUT, IN OUT} ,<data type>) {IS, AS} Variable declaration Constant declaration BEGIN PL/SQL statement EXCEPTION Statement END;
55
example CREATE OR REPLACE PROCEDURE PROC2(N1 IN NUMBER, N2 IN NUMBER, TOTAL OUT NUMBER) IS BEGIN TOTAL:=N1+N2; END; / SQL> VARIABLE TOTAL NUMBER SQL> EXEC PROC2(12,12,:TOTAL) PL/SQL procedure successfully completed. SQL> PRINT TOTAL TOTAL 24
56
REPLACE Recreates the procedure if already exists Schema The oracle engine takes the default schema to be current schema, if it is omitted Procedure Name of procedure IN Indicates that the parameter will accept a value from the user. OUT Indicates that the parameter will return a value to the user. IN OUT Indicates that the parameter will either accept a value from the user or return a value to the user Data_type Is the data type of an argument.
57
function Syntax CREATE OR REPLACE FUNCTION [SCHEMA] <functionName> (<ARGUMENT> IN <data type>) RETURN <Data type> (IS, AS) Variable declaration Constant declaration BEGIN PL/SQL statement EXCEPTION Statement END;
58
REPLACE Recreates the function if already exists Schema The oracle engine takes the default schema to be current schema, if it is omitted Function Is the name of function to be created Argument Is the name of an argument to the function, parentheses can be omitted if no arguments are present. IN Indicates that the parameter will accept a value from the user RETURN DATA Type Is the data type of function’s return value. Because every function must return a value, this clause is required.
59
example CREATE OR REPLACE FUNCTION CIRCLE_AREA(P_RADIUS IN NUMBER) RETURN NUMBER AS v_pi NUMBER := 3.14; v_area NUMBER; BEGIN v_area := v_pi * POWER(p_radius, 2); RETURN v_area; END; /
60
Example SQL> SELECT CIRCLE_AREA(12) FROM DUAL; CIRCLE_AREA(12)
CIRCLE_AREA(12) 452.16
61
These database objects consist following distinct sections:
Database triggers Database triggers are database objects created via the SQL * Plus tool on the client and stored on the server. These database objects consist following distinct sections: A named database event A PL/SQL block that will execute when event occurs.
62
Database triggers The oracle engine allows the definition of procedures that are implicitly executed, when an insert, update or delete is issued against a table from SQL* Plus or through an application. These procedures are called database trigger.
63
Use of trigger A trigger can also be used to keep track of a table i.e. store the modified and delete record of the table. It can be used to prevent invalid transaction. Enforce complex security authorization.
64
Triggers v/s procedures
Trigger do not accept parameters where as procedures can. Triggers is executed implicitly by the oracle engine To execute procedure, it has to explicitly called by a user.
65
How to apply database triggers
A trigger has three basic parts A triggering event or statement. It is a SQL statement that causes a trigger to fired. It can be INSERT, UPDATE OR DELETE statement for a specific table. A trigger restriction A trigger restriction specifies a Boolean expression that must be TRUE for the trigger to fire. A trigger restriction is specified using a WHEN clause. A trigger action A trigger action is the PL/SQL code to be executed when a triggering statement is encountered.
66
Types of triggers Row Triggers:- A row trigger is fired each time a row in the table is affected by the triggering statement. For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement. It the triggering statement affects no rows, the trigger is not executed at all.
67
A statement trigger fired once on behalf of the triggering statement.
Statement trigger should be used when a triggering statement affects rows in a table but the processing required is completely independent of the number of rows affected.
68
Before v/s after triggers
When defining a trigger it is necessary to specify the trigger timing. i.e. specify when the triggering action is to be executed in relation to the triggering statement. BEFORE and AFTER apply to both row and the statement triggers.
69
syntax CREATE OR REPLACE TRIGGER <TriggerName> {BEFORE, AFTER}
{DELETE, INSERT, UPDATE [OF COLUMN…]} ON <TableName> [REFERENCING { OLD AS old, NEW AS new}] [FOR EACH ROW [WHEN condition]] DECLARE <variable declaration>; <constant declaration>; BEGIN <PL/SQL subprogram body>; EXCEPTION END;
70
KEYWORDS AND PARAMETERS
OR REPLACE Recreate the trigger if already exists TriggerName Is the name of the trigger to be created. BEFORE Indicates that the Oracle engine fired the trigger before executing the triggering statement AFTER Indicates that the Oracle engine fired the trigger after executing the triggering statement DELETE Indicates that the Oracle engine fires the trigger whenever a DELETE statement removes a row from the table. INSERT Indicates that the Oracle engine fires the trigger whenever an INSERT statement adds a row to table. UPDATE Indicates that the Oracle engine fires the trigger whenever an UPDATE statement changes a values in one of the column specified in the OF clause. ON Specify the schema and name of the table, which the trigger is to be created
71
REFERENCING Specifies corelation names. Correlation names can be used in the PL/SQL block and WHEN clause of row trigger to refer specifically to old and new value of the current row. The default correlation names are OLD and NEW. FOR EACH ROW Designates the trigger to be a row trigger. The Oracle engine fires a row trigger once for each row that is affected by the triggering statement and meets the optional trigger constraint defined in the WHEN clause. WHEN Specifies the trigger restriction. The trigger restriction contains a SQL condition that must be satisfied for the Oracle engine to fire the trigger.
72
Example
73
CREATE TRIGGER AUDIT_TRAIL AFTER UPDATE OR DELETE
ON PERSON FOR EACH ROW DECLARE OPER VARCHAR2(8); BEGIN IF updating THEN OPER:='UPDATE'; END IF; IF DELETING THEN OPER:='DELETE'; INSERT INTO RECORD VALUES(:OLD.P_ID,:OLD.LASTNAME,:OLD.FIRSTNAME,:OLD.ADD RESS,:OLD.CITY); END; /
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.