Documente Academic
Documente Profesional
Documente Cultură
Prerequisites
Prior knowledge of Oracle database Prior knowledge of DDL, DML & SQL Language Oracle 9i/10g installation on trainee desktop SQL*Plus utility installed Editor Notepad / Wordpad
Introduction
PL/SQL stands for Procedural Language/SQL PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural language that is more powerful than SQL PL/SQL is a modern, block-structured programming language PL/SQL provides several features that make developing powerful database applications very convenient The basic unit in PL/SQL is a block. All PL/SQL programs are made up of blocks, which can be nested within each other
Introduction
PL/SQL blocks can have both SQL data manipulation language (DML), and data definition language (DDL) statements PL/SQL provides procedural constructs, such as loops and conditional statements, that are not available in standard SQL PL/SQL offers features such as Data Encapsulation, Exception Handling, Information Hiding, Object Orientation
Architecture
Architecture
Stored procedure compilation produces object code which is interpreted by pl/sql engine. Native compilation into byte-code is possible from oracle 9i Stored Procedures are loaded in Library cache in shared pool of SGA. This is controlled by shared_pool_size init.ora parameter Pin the stored procedure in memory to improve performance. Oracle provides API to do this execute dbms_shared_pool.keep('DBMS_ALERT'); Pinning should be done after every start up View v$db_object_cache provides list of all objects in shared pool cache
Benefits of PL/SQL
Improved performance PL/SQL can be used to group SQL statements together within a single block and to send the entire block to the server in a single call, thereby reducing networking traffic
SQL SQL
Application
SQL SQL
SQL
Other DBMSs
Application
Benefits of PL/SQL
Group logically related statements within blocks Nest sub-blocks inside larger blocks to build powerful programs Break down a complex problem into a set of manageable, well-defined, logical modules and implement the modules with blocks PL/SQL is portable. Can be invoked from other environments You can program with procedural language control structures
Benefits of PL/SQL
Error Handling Improved data security and integrity Improved performance allows you to : Avoid reparsing for multiple users by exploiting the shared SQL area Avoid PL/SQL parsing at run time by parsing at compile time Reduce the number of calls to the database and decrease network traffic by bundling commands
1 2
xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv
LOG_EXECUTION procedure
xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv xxxxxxxxxxxxxx vvvvvvvvvvvvvv
Oracle Portal
Oracle Discoverer
Scott
10
Block Structure
A PL/SQL block consists of an optional declaration section an execution section and one or more optional exception handler sections Declaration section declares PL/SQL variables, exceptions, and cursors Execution section contains PL/SQL code and SQL statements, control structures (loops), conditional statements (IFEND IF) and can contain nested blocks Exception handler section contain code that is called when the exception is raised, either as a predefined PL/SQL exception or as an exception that you define
11
Block Structure
DECLARE [Optional] [<Block header>] [declare] <Constants> <Variables> <Cursors> <User defined exceptions> [begin] <PL/SQL statements> [exception] <Exception handling> end;
BEGIN [Mandatory]
EXCEPTION [Optional]
END; [Mandatory]
12
Types of PL/SQL
Anonymous block Stored Procedure Function Package Trigger
13
Anonymous Block
An anonymous block is a PL/SQL program unit that has no name An anonymous block cannot take input arguments and return output values cannot be called concurrently by multiple users is not stored in the data dictionary Anonymous blocks are usually used interactively from a tool, such as SQL*Plus, or in a precompiler, OCI, or SQL*Module application They are usually used to call stored procedures or to open cursor variables
14
Examples
Example1: SQL> set serveroutput on SQL> BEGIN 2 dbms_output.put_line(Welcome to PL/SQL); 3 END; 4 /
16
Examples
Example2: DECLARE Emp_number INTEGER := 7369; Emp_name VARCHAR2(10); BEGIN SELECT Ename INTO Emp_name FROM Emp WHERE Empno = emp_number; DBMS_OUTPUT.PUT_LINE('Employee name is ' || Emp_name); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('No such employee: ' || Emp_number); END; /
2003 Accenture All Rights Reserved. 17
Declaring Variables
Agenda
Basic PL/SQL Block and Its Sections Significance of Variables in PL/SQL Distinguishing Between PL/SQL and Non-PL/SQL Variables Declaring Variables and Constants Executing a PL/SQL Block
19
Program Section
20
Significance of Variables
Variables can be used for: Temporary storage of data Manipulation of stored values Reusability Ease of maintenance This is facilitated by the way variables are handled in PL/SQL: Variables are declared and initialized in the declaration section Variables are assigned new values in the executable section Values are passed to PL/SQL blocks through parameters Output variables are used to view the results
21
22
PL/SQL Datatypes
23
24
25
Examples
v_hiredate v_deptno v_location v_mgr c_comm DATE; NUMBER(2) NOT NULL := 10; VARCHAR2(13) := 'Atlanta'; NUMBER(6) DEFAULT 100; CONSTANT NUMBER := 1400;
The Variable name should not be more than 30 characters Adopt a naming convention for PL/SQL identifiers: for example, v_variablename
2003 Accenture All Rights Reserved. 26
27
Scope of Variable
Declare A number; Begin declare B number; begin declare C number; begin ..Statements end; ..Statements.. end; ..Statements.. end; / Scope of Variable C is limited to the block displayed in RED Scope of Variable B is limited to the block displayed in GREEN Scope of Variable A is across block displayed in BLUE
28
Agenda
Identifying the Uses and Types of Control Structures Constructing Conditional Statements Constructing and Identifying Different Loop Statements Controlling Block Flow Using Nested Loops and Labels
30
Constructing IF Statements
IF Conditional Statement... IF condition THEN sequence_of_statements; [ELSIF condition THEN sequence_of_statements;] [ELSE sequence_of_statements;] END IF; Conditions must evaluate to either TRUE or FALSE. Statements are executed only when the associated condition evaluates to TRUE. If the condition evaluates to NULL, those statements corresponding to that condition will not be executed. Can have as many ELSIF sections as required, but only one IF and ELSE section.
2003 Accenture All Rights Reserved. 32
The test_variable can be simply a variable or an expression which call a function to get the value. ELSE section is optional, and if the expression does not match any value and if there is no ELSE section in the CASE statement, it will throw CASE_NOT_FOUND error. A label after END CASE is legal only if the CASE statement itself is labeled, and the two labels must match.
33
Example: IF Statement
Declare V_sal emp.sal%type; V_emp_name emp.ename%type; Begin Select ename, sal into v_emp_name, v_sal from emp where empno = 7369; If v_sal > 5000 then dbms_output.put_line(Salary is greater than 5000); Else dbms_output.put_line(Salary is less than 5000); End if; End; /
34
35
LOOP Statements
LOOP Statement LOOP statements; EXIT [WHEN condition]; END LOOP; WHILE LOOP Statement WHILE condition LOOP statements; END LOOP; In a normal loop statement EXIT statement can come at any point in the sequence of statements inside the loop statement While loop can also contain an EXIT statement Number of iterations is not known in either of the LOOP or WHILE LOOP statements Loops also can be labeled, which will be useful while using nested loops
37
38
LOOP Statements
Counter is an implicitly declared variable FOR LOOP Statements FOR counter IN [REVERSE] l_bound..u_bound LOOP Difference of l_bound and u_bound specifies the number of iterations that a FOR LOOP will perform While entering FOR LOOP counter will be assigned the value of l_bound and incremented by 1 for every iteration till it reaches the value of u_bound REVERSE key word is optional: If reverse key word is used, counter will be assigned the value of u_bound and decremented by 1 for every iteration till it reaches the value of l_bound.
2003 Accenture All Rights Reserved. 39
statements;
END LOOP;
40
41
Agenda
Writing a Successful SELECT Statement in PL/SQL Declaring the Data type and Size of a PL/SQL Variable Dynamically Writing Data Manipulation Language (DML) Statements in PL/SQL Controlling Transactions in PL/SQL Determining the outcome of SQL DML Statements Writing Explicit Cursors
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
Cursors in PL/SQL
CURSOR 1. For every SQL statement execution certain area in memory is allocated 2. PL/SQL allows you to name this area - Context Area/Cursor 3. Cursor represents a structure or result set in memory CURSOR Variable 1. Writing a Cursor in the PL/SQL - Declaring Cursor Variable 2. Opening Cursor - Cursor Variable points to the Context Area/Cursor Types of cursors 1. Implicit Cursor 2. Explicit Cursor
58
CURSOR Attributes
%NOTFOUND It is a Boolean attribute, which evaluates to true, if the last fetch failed i.e. when there are no rows left in the cursor to fetch %FOUND Boolean variable, which evaluates to true if the last fetch, succeeded %ROWCOUNT Its a numeric attribute, which returns number of rows fetched by the cursor so far %ISOPEN A Boolean variable, which evaluates to true if the cursor is opened otherwise to false
2003 Accenture All Rights Reserved. 59
60
CURSOR Operations
DECLARE CURSOR <cursor-name> IS <select statement>; OPEN OPEN <cursor-name>; FETCH FETCH <cursor-name> INTO <var1,var2,...>; CLOSE CLOSE <cursor-name>;
62
64
65
66
68
69
Parameterized Cursors
A Parameterized Cursor takes arguments, similar to a PL/SQL Procedure or Function We do not have to hardcode any value in the WHERE clause, instead we can pass the variable as a parameter to the cursor If we are using the same SQL statement with different WHERE clauses, instead of writing cursors for each of the different criteria, we can generalize the cursor by declaring a parameterized cursor The scope of the cursor parameter is confined to that cursor Only the syntax of Declaring and Opening the cursor differs, with the normal cursor operation syntax Observe that cursor can have IN parameters only unlike in procedures and functions we have IN, OUT and IN OUT as the mode of parameter
71
72
73
74
75
76
78
Composite Datatypes
Agenda
PL/SQL Table PL/SQL Record
81
PL/SQL Table
A PL/SQL table is a one-dimensional, unbounded, sparse collection of homogeneous elements, indexed by integers It is analogous to an array and a SQL table A PL/SQL table is one type of collection structure
82
1 2 3
2003 Accenture All Rights Reserved.
84
86
88
89
Direct assignment
DECLARE TYPE tab_type IS TABLE OF NUMBER INDEX BY binary_integer; iter_tab tab_type; BEGIN iter_tab(1) := 100; iter_tab(2) := 200; iter_tab(3) := 300; iter_tab(4) := 400; FOR j IN 1..iter_tab.count LOOP DBMS_OUTPUT.PUT_LINE(to_char(iter_tab(j))); END LOOP; END; /
2003 Accenture All Rights Reserved. 90
Iterative assignment
DECLARE TYPE tab_type IS TABLE OF NUMBER INDEX BY binary_integer; iter_tab tab_type; BEGIN FOR i IN 1..10 LOOP iter_tab(i) := i+10; END LOOP; FOR j IN 1..10 LOOP DBMS_OUTPUT.PUT_LINE(to_char(iter_tab(j))); END LOOP; END; /
2003 Accenture All Rights Reserved. 91
Aggregate assignment
DECLARE TYPE name_table IS TABLE OF VARCHAR2(100) INDEX BY BINARY_INTEGER; old_names name_table; new_names name_table; BEGIN /* Assign values to old_names table */ old_names(1) := 'Smith'; old_names(2) := 'Harrison'; /* Assign values to new_names table */ new_names(111) := 'Hanrahan'; new_names(342) := 'Blimey';
92
Aggregate assignment
/* Transfer values from new to old */ old_names := new_names; /* This assignment will raise NO_DATA_FOUND */ DBMS_OUTPUT.PUT_LINE (old_names (1)); END; /
93
94
96
PL/SQL Record
PL/SQL record is a composite data structure similar to a singlerow of a database table PL/SQL record as a whole does not have value of its own; instead, each individual component or field has a value PL/SQL record gives you a way to store and access individual component values as a group
98
Example:
Field1 (data type) Field2 (data type) Field3 dept_id number(2) dept_name varchar2(14) dept_loc varchar2(13) ACCOUNTING (data type)
10
NEW YOR
99
Cursorbased
A record based on Each field corresponds to a column the cursor's SELECT or expression in the cursor SELECT statement. statement Each field is defined explicitly (its name and datatype) in the TYPE statement for that record; a field in a programmer-defined record can even be another record.
Programmer- A record whose defined structure you, the programmer, get to define with a declaration statement.
2003 Accenture All Rights Reserved.
100
101
Programmer-Defined Records
PL/SQL record which is a sub-set of table columns or from multiple tables or views DECLARE TYPE emp_type IS RECORD (r_ename VARCHAR2(10), r_dname VARCHAR2(10)); emp_rec emp_type; BEGIN SELECT ename,dname INTO emp_rec.r_ename, emp_rec.r_dname FROM dept,emp WHERE dept.deptno=emp.deptno and emp.empno= 7369; DBMS_OUTPUT.PUT_LINE('Dept name is : '||emp_rec.r_dname); DBMS_OUTPUT.PUT_LINE('Emp name is : '||emp_rec.r_ename); END; /
2003 Accenture All Rights Reserved. 104
Exception Handling
Agenda
PL/SQL Error Handling Exception Handler Mechanism User Defined Exception PRAGMA Exception
106
107
Exception Types
There are Two types of exceptions System Defined Raised automatically by the system when error occurs User Defined Raised explicitly in a sequence of statements using raise <exception name> Format when <exception name> then <sequence of statements>;
110
Exception Handling
Trap the exception DECLARE BEGIN EXCEPTION END; END; Propagate the exception DECLARE BEGIN
Common Exceptions
System Exceptions the most common errors Exception Name Number Remarks Try to open a cursor which is already exist Invalid Cursor operation like fetching from a closed cursor Select statement returns no data Expected one row but returned more than one Try to divide a number by 0.
112
Generic Exception
OTHERS EXCEPTION HANDLER Can be used as a generic exception handler Example DECLARE a number; BEGIN SELECT 1 INTO a FROM emp WHERE empno='99'; EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(Error ||SQLCODE||' - '||SQLERRM); END; /
2003 Accenture All Rights Reserved.
Note: SQLCODE - Returns the number of the Oracle error for internal exceptions SQLERRM - Returns the message associated with the error number
113
114
115
116
117
error_number is a negative integer in the range 20000 .. -20999 message is a character string up to 2048 bytes long If TRUE, the error is placed on the stack of previous errors If FALSE (the default), the error replaces all previous errors
118
119
120
PRAGMA Exception
Apart from predefined exception, we can extend the list of exceptions associated with an Oracle error within our PL/SQL code with the use of PRAGMA EXCEPTION_INIT keyword EXCEPTION PRAGMA is used to associate a named exception with a particular Oracle error This enable us to trap the error specifically, rather than via an OTHERS handle Only one user defined exception can be associated with one Oracle error with each occurrence of PRAGMA EXCEPTION_INIT This statement is a compiler directive that allows the developer to declare the Oracle-numbered error to be associated with a named exception in the block
121
PRAGMA Exception
Example declare empname VARCHAR2(12); no_record EXCEPTION; PRAGMA EXCEPTION_INIT(no_record, 100); BEGIN select ename into empname from emp where empno=&9999; dbms_output.put_line('Name :'||empname); EXCEPTION when no_record then dbms_output.put_line('Error code is ' || SQLCODE); dbms_output.put_line('Error message is '||SQLERRM); dbms_output.put_line('No Record found'); END; /
2003 Accenture All Rights Reserved. 122
PRAGMA Exception
Example 2 Trap for Oracle server error number 2292, an integrity constraint violation DECLARE p_deptno number := &deptno; e_emps_remaining EXCEPTION; PRAGMA EXCEPTION_INIT (e_emps_remaining, -2292); BEGIN DELETE FROM dept WHERE deptno = p_deptno; IF SQL%NOTFOUND THEN DBMS_OUTPUT.PUT_LINE ('No such dept '||to_char(p_deptno)); END IF; EXCEPTION WHEN e_emps_remaining THEN DBMS_OUTPUT.PUT_LINE ('Cannot remove dept ' || TO_CHAR(p_deptno) || '. Employees exist. '); END;
2003 Accenture All Rights Reserved. 123
PL/SQL Subprograms
Agenda
Subprogram Structure Stored Procedures Procedure Parameter Modes Functions Overloading
125
127
Stored procedure
A named PL/SQL block that performs one or more actions and is called as an executable PL/SQL statement A Program can pass information into and out of a procedure through its parameter list A stored procedure is defined by the keywords CREATE PROCEDURE followed by the procedure name and its parameters There can be any number of parameters, each followed by a mode and a type. The possible modes are IN (read-only), OUT (write-only), and INOUT (read and write)
128
Stored Procedure
Syntax CREATE [or REPLACE] PROCEDURE <procedure name> [(<list of parameters>)] IS <declarations> BEGIN <sequence of statements> [EXCEPTION <exception handling routines>] END [<procedure name>]; IN | OUT | INOUT Parameter <parameter name> [IN | OUT | IN OUT] <data type> [{ := | DEFAULT} <expression>]
129
Parameter Mode IN
IN - The IN parameter allows you to pass values in to the module, but will not pass anything out of the module and back to the calling PL/SQL block IN parameters function like constants. Just like constants, the value of the formal IN parameter cannot be changed within the program. You cannot assign values to the IN parameter or in any other way modify its value IN is the default mode for parameters IN parameters can be given default values in the program header
131
Parameter Mode - IN
Example Create or Replace Procedure MyProc2 (I_empno IN number) is Emp_name VARCHAR2(10); Begin SELECT Ename INTO Emp_name FROM Emp WHERE Empno = i_empno; Dbms_output.put_line('Employee name is ' || Emp_name); Exception WHEN NO_DATA_FOUND THEN Dbms_output.put_line('No such employee: ' || i_empno); End; /
132
135
136
Discovering Errors
PL/SQL does not always tell you about compilation errors. Instead, it gives you a cryptic message such as "procedure created with compilation errors" To show the compilation error use the command SQL> show errors procedure <procedure_name>; Alternatively, you can type, SHO ERR (short for SHOW ERRORS) to see the most recent compilation error
137
Function
A named PL/SQL block that returns a single value and is used just like a PL/SQL expression A program can pass information into a function through its parameter list Unlike a procedure, which is a standalone executable statement, a call to a function can only be part of an executable statement Because a function returns a value, it has a datatype A function can be used in place of an expression in a PL/SQL statement having the same datatype as the function
138
Function
CREATE or <REPLACE> FUNCTION <func_name>(<param_list>) RETURN <return_type> IS BEGIN <sequence of statements> [EXCEPTION <exception handling routines>] END [<function name>];
139
Function
Example CREATE or REPLACE FUNCTION total_sal (p_empno IN number) RETURN NUMBER is n_total NUMBER; BEGIN SELECT nvl(sal,0)+nvl(comm,0) INTO n_total FROM emp WHERE empno = p_empno; RETURN(n_total); EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE('Error occurred for emp : '|| to_char(p_empno)); RETURN(0); END; /
2003 Accenture All Rights Reserved. 140
Overloading
Two or more Procedures/Functions can have the same name with different parameter lists The parameter list of overloaded programs must differ by more than parameter mode Even if a parameter in one version is IN and that same parameter is IN OUT in another version, PL/SQL cannot tell the difference at the point in which the program is called Overloaded functions must differ by more than their return type (the datatype specified in the RETURN clause of the function) All of the overloaded programs must be defined within the same PL/SQL scope or block (anonymous block, module, or package)
142
SQL>
SQL>
143
Dropping Function/Procedure
Syntax To Drop a Stored Procedure DROP <Procedure> <Procedure_Name>; To Drop a Function DROP <Function> <Function_Name>; Example DROP FUNCTION total_sal; / DROP PROCEDURE MyProc; /
2003 Accenture All Rights Reserved. 144
Triggers
Agenda
Definition and Advantages Types of Triggers INSTEAD OF Triggers Manipulating Triggers
146
Types of Triggers
Oracle supports Event Triggers in addition to the SQL Statement and Row triggers Oracle statement and row triggers are based on three types of SQL statements: INSERT, UPDATE, and DELETE The trigger timing may be either BEFORE" or AFTER Statement-level triggers fire only once per SQL statement, regardless of how many rows were processed Row-level triggers fire once for each row that is affected by the SQL statement In addition to these, Oracle supports INSTEAD OF" triggers that are valid only on views
148
149
150
151
INSTEAD OF Trigger
Application
INSERT INTO my_view . . .;
INSTEAD OF Trigger
INSERT TABLE1
MY_VIEW
2003 Accenture All Rights Reserved.
UPDATE TABLE2
152
153
Manipulating Triggers
Altering triggers: ALTER TRIGGER trigger_name ENABLE|DISABLE; ALTER TABLE table_name ENABLE|DISABLE all triggers; Dropping triggers: DROP TRIGGER trigger_name; The following data dictionary views reveal information about triggers: -USER_TRIGGERS -ALL_TRIGGERS -DBA_TRIGGERS
2003 Accenture All Rights Reserved. 156
Packages
A package is a group of procedures, functions, variables and SQL statements created as a single unit. It is used to store together related objects. A package has two parts, Package Specification or package header and Package Body. Package Specification acts as an interface to the package. Declaration of types, variables, constants, exceptions, cursors and subprograms is done in Package specifications. Package specification does not contain any code. Package Body is used to provide implementation for the subprograms, queries for the cursors declared in the package specification or spec.
157
Advantages of Packages
Package allows you to group together related items, types and subprograms as a PL/SQL module. When a procedure in a package is called entire package is loaded, though it happens to be expensive first time the response is faster for subsequent calls. Package allows us to create types, variable and subprograms that are private or public
2003 Accenture All Rights Reserved. 158
159
160
161
163
End P_Dept; /
164
166
DBMS_PROFILER
Since Oracle 8i we can trace pl/sql like we can trace sql with tkprof. With DBMS_PROFILER you can measure the execution time of a pl/sql program unit. DBMS_PROFILER gives insight into the following statistics: - The number of times a piece of pl/sql was executed - The total time spend on a piece of pl/sql code, including sql statements. - Minimum and maximum time spend on a piece of pl/sql code - Which code is executed during profiling.
167
Prerequisites
The DBMS_PROFILER package is not automatically created on install of the database. Before you can use it, you should run the following scripts: as sys user run the $ORACLE_HOME/rdbms/admin/profload.sql script. As user that uses the profiler (or as sys with grants) run: $ORACLE_HOME/rdbms/admin/proftab.sql
2003 Accenture All Rights Reserved. 168
Procedures
The DBMS_PROFILER package has the following procedures: Start_Profiler: begin data collection Stop_Profiler: stop data collection. Data is not automatically stored when the user disconnects. Flush_Data: flush data collected in user session. Can call at points in a run to get incremental data. Pause_Profiler: pause user data collection Resume_Profiler: resume data collection Get_Version (proc): gets the version of this api. Internal_Version_Check: verify that the DBMS_Profiler version works with this DB version.
169
Tables
The profiler-information is stored in the following tables: plsql_profiler_runs - information on profiler runs plsql_profiler_units - information on each line profiled plsql_profiler_data - profiler data for each line profiled
170
171
172
173