Professional Documents
Culture Documents
Cognizant 500 Glen Pointe Center West Teaneck, NJ 07666 Ph: 201-801-0233 www.cognizant.com
TABLE OF CONTENTS
Introduction ...................................................................................................................................5 About this Module .........................................................................................................................5 Target Audience ...........................................................................................................................5 Module Objectives ........................................................................................................................5 Pre-requisite .................................................................................................................................5 Session 02: PL/SQL Fundamentals ..............................................................................................6 Learning Objectives ......................................................................................................................6 PL/SQL Features ..........................................................................................................................6 PL/SQL Architecture .....................................................................................................................6 PL/SQL Block Structure................................................................................................................8 Identifiers ......................................................................................................................................9 Variables .......................................................................................................................................9 Data Types .................................................................................................................................11 PL/SQL Statements ....................................................................................................................12 Expressions and Operators ........................................................................................................12 Conditional and Loop Constructs ...............................................................................................13 Summary ....................................................................................................................................16 Test Your Understanding............................................................................................................16 Session 05: PL/SQL Subprograms .............................................................................................17 Learning Objectives ....................................................................................................................17 Understand Subprograms ..........................................................................................................17 Procedures .................................................................................................................................18 Functions ....................................................................................................................................20 Procedure VS Function ..............................................................................................................23 Packages ....................................................................................................................................23 Oracle Supplied Packages .........................................................................................................25 Summary ....................................................................................................................................26 Test Your Understanding............................................................................................................26 Session 07: Triggers ....................................................................................................................27 Learning Objectives ....................................................................................................................27 Appreciate Database Triggers ....................................................................................................27 Components of Triggers .............................................................................................................27
Page 2 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 3 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 4 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Introduction
About this Module
The module provides an overview about the basics of PL/SQL statements in Oracle.
Target Audience
This module is designed for the entry level trainees.
Module Objectives
After completing module, you will be able to: Write PL/SQL statements Write Static and Dynamic SQL statements Create procedures, functions, packages, and triggers Use static and dynamic cursors in PL/SQL blocks
Pre-requisite
The trainees need to have an idea of the following: General Programming and Logic Structured Query Language Relational DBMS
Page 5 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
PL/SQL Features
PL/SQL stands for Procedural Language/SQL PL/SQL extends SQL by adding constructs found in other procedural languages Variables and types Control Structures (IF-THEN-ELSE) Procedures and Functions Object types and methods Need of PL/SQL Procedural Language/Structured Query Language is an extension to SQL PL/SQL provides programming facility to the users Set of instructions that can be stored in the server as Database Objects in compiled form
PL/SQL Architecture
How PL/SQL Works Blocks of PL/SQL statements are translated by the PL/SQL engine that can reside either in the client or at the server side. It divides the SQL statements from PL/SQL block and sends them to SQL STATEMENT EXECUTOR. The output finally comes to the client end.
Page 6 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 7 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Section Declarative
Description Contains all variables, constants, cursors and user defined exceptions that are referenced in the executable and declarative sections. Contains SQL statements to manipulate data in the database and PL/SQL statements to manipulate data in the block.
Inclusion Optional
Executable
Mandatory
Exception handling Specifies the actions to perform when errors and abnormal conditions arise in the executable section
Optional
Page 8 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Identifiers
Can contain up to 30 characters. Must begin with an alphabetic character. Can contain numerals, underscores, dollar sign, and number signs. Can not contain characters such as hyphens, slashes, and spaces. Should not have the same name as a database table column name. Should not be reserved words. You can use the Identifiers to do the followings: Declare variables, constants, cursors and exceptions and then use them in SQL and procedural statements. Declare variables belong to scalar, reference, composite and large object (LOB) data types. Declare variables dynamically based on the data structure of tables and columns in the database.
Variables
Variables are memory locations, which can store data values Information from database can be assigned to a variable, or the contents of a variable can be inserted into the database The variables are declared in the declarative section of the block Every variable has a specific type which describes what kind of information it can store
Page 9 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Declare and initialize variables in the declaration sections. Assign new value to variable in the executable section. Pass values into PL/SQL blocks through parameters. View result through output variables.
Type of variables:
PL/SQL variables: Scalar Composite Reference LOB (large objects) Non PL/SQL variables: Bind Host Bind Variables: A bind variable is a variable that you declare in a host environment. Bind variables can be used to pass run time values either number or character, into or out of one or more PL/SQL program. Declare the variable in SQL * PLUS environment by VARIABLE key word. VARIABLE return_code number HOST Variables: You can access HOST variables in PL/SQL program. VARIABLE result number These variable should proceeded by a colon. : Result
Page 10 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Data Types
Scalar data types hold a single value. Composite data types allow group of fields to be defined and manipulated in PL/SQL blocks. Reference data types hold values that designate other program item. LOB (large objects) data types hold values, called locators that specify the location of the large object (such as graphic images) that are stored out of line. Base Scalar data types are as follows: CHAR [(maximum_length)] VARCHAR2(maximum_length) LONG LONG RAW NUMBER[(precision , scale)] BINARY_INTEGER PLS_INTEGER BOOLEAN DATE TIMESTAMP TIMESTAMP WITH TIME ZONE TIMESTAMP WITH LOCAL TIME ZONE INTERVAL YEAR TO MONTH INTERVAL DAY TO SECOND Composite data types: Composite data types also known as collections are of following types TABLE RECORD NESTED TABLE VARRAYS LOB data types: With the LOB data types you can store blocks of unstructured data (such as text, graphic images, video clips) up to 4GB. CLOB: The CLOB (Character Large Object) data type is used to store large blocks of single byte character data in the database in line (inside the row) or out line (outside the row). BLOB: The BLOB (binary large object) data type is used to store binary large objects data in the database in line (inside the row) or out line (outside the row). BFILE: The BFILE (binary file) data type is used to store large binary objects in operating system files outside the database. NCLOB: The (National Character Large Object) data type is used to store large blocks of single byte or fixed width multi-byte NCHAR Unicode data in the database in line (inside the row ) or out line (outside the row) .
Page 11 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
PL/SQL Statements
Statements in PL/SQL The INTO clause must be used to store a table column value into a variable declared in the DECLARATION section of PL/SQL block SELECT ENAME INTO MEMNAME FROM EMP WHERE EMPNO=101176; Multiple column values can be assigned to equal number of memory variables using single INTO SELECT ENAME, SAL INTO MEMNAME, MEMSAL FROM EMP WHERE EMPNO=101176;
Page 12 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Comparison Operators: Comparison operators are used in conditions that compare one expression to another. The result of comparing one expression to another can be TRUE, FALSE, or UNKNOWN. Below is given an example of a comparison Operator: Operator + Purpose Equality Test Example SELECT * FROM emp WHERE sal=1500
Logical Operators: A logical operator combines the results of two component conditions to produce a single result based on them or to invert the result of a single condition. The main comparison operators are: AND, Not and OR Below is given an example of a comparison Operator: Operator Function Returns TRUE if the following condition is FALSE. Returns FALSE if it is TRUE. If it is UNKNOWN, it remains UNKNOWN Example SELECT * FROM emp WHERE NOT (sal BETWEEN 1000 AND 2000)
NOT
Set Operators: Set operators combine the results of two component queries into a single result. Queries containing set operators are called compound queries. The main set operators are: UNION, UNION ALL, INTERSECT and MINUS Expression: An expression is a sequence of variables and literals, separated by operators. The most basic operator is assignment. Syntax Variable: = expression Variable is PL/SQL variable and expression is PL/SQL expression PL/SQL expression is: 3 + 5 * 7 Concatenation operator (||) attaches two or more strings together. For example, the expression Hello ||World evaluates to Hello World.
Page 14 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 15 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Summary
A PL/SQL block can be anonymous block or named block. Variables are memory locations, which can store data values Variables declare in external environment are called host variable. Scalar data types hold a single value. Composite data types allow group of fields to be defined and manipulated in PL/SQL blocks. An expression is a sequence of variables and literals, separated by operators. You can change the logical flow of statements within the PL/SQL block with the following control structures. o IF-THEN-ELSE o LOOPS o WHILE LOOPS o FOR LOOPS
Page 16 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Understand Subprograms
Is a named PL/SQL block that can accept parameters and be invoked from a calling environment Is of two type: A procedure that performs an action A function that computes a value. Is based on standard PL/SQL block structure. Provides modularity, reusability, extensibility and maintainability.
Block structure for PL/SQL subprograms The header is relevant for named blocks only and determines the way that the program unit is called or invoked. The header determines: The PL/SQL subprogram type, that is, either a procedure or a function The name of the subprogram The parameter list, if one exists The RETURN clause, which applies only to functions The IS or AS keyword is mandatory.
Page 17 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Procedures
What is a Procedure? It is a sub program in the PL/SQL block, which can perform a specific task when invoked explicitly with or without parameter. A Procedure has two parts: Specification and Body Specification: This section begins with the keyword Procedure followed by its name and Parameter list (optional) Body: Procedure Body begins with the keyword IS/AS and ends with the keyword END followed by the procedure name (optional) Syntax: CREATE OR REPLACE PROCEDURE <PROCEDURE_NAME> (<PARAMETER> [MODE] <DATA TYPE>,) IS/AS [LOCAL VARIABLE DECLARATION] BEGIN PL/SQL EXECUTABLE STATEMENT [EXCEPTION] [EXCEPTION HANDLERS] END [PROGRAM UNIT NAME]; In Syntax: [REPLACE]: Option indicates that if the procedure exists, it will be dropped and replaced with the new version created by the statement. <parameter>: Name of a PL/SQL variable whose value is passed to or populated by the calling environment, or both, depending on the mode being used [Mode ]: Type of argument: IN (default), OUT, IN OUT <Data type>: Data type of the argumentcan be any SQL / PLSQL data type. PL/SQL block starts with either BEGIN or the declaration of local variables and ends with either END or END procedure_name.
Page 18 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
AS
Page 19 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Functions
Function is a named PL/SQL block that returns a value. A function can be stored in the database as a schema object for repeated execution. A function is called as part of an expression. Functions can be used in a SELECT statement.
Page 20 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 21 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
To be callable from SQL expressions, a user-defined function must: Be a stored function Accept only IN parameters Accept only valid SQL data types, not PL/SQL Specific types, as parameters Return data types that are valid SQL data types, Not PL/SQL specific types Removing a Function: DROP FUNCTION <function_name> DROP FUNCTION fn_service_tax; All the privileges granted on a function are revoked when the function is dropped. The CREATE OR REPLACE syntax is equivalent to dropping a function and recreating it. Privileges granted on the function remain the same when this syntax is used.
Page 22 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Procedure VS Function
Procedures Execute as a PL/SQL statement Do not contain RETURN clause in the header Can return none, one, or many values Can contain a RETURN statement Functions Invoke as part of an expression Must contain a RETURN clause in the header Must return a single value Must contain at least one RETURN statement
Packages
What is a Package? A package is a collection of Functions, Procedures, Global variables and cursors stored in server in compiled form. A package consists of 2 parts: Package Specification: This acts as an interface to the user applications. This part declares the, PL/SQL types, variables, constants, exception, cursor and sub-programs (Functions and procedures). This part is created using CREATE PACKAGE command. Package Body: It implements the specifications by defining the cursors and sub-programs. This part is created using CREATE PACKAGE BODY command. Oracle stores package specification and body separately in the data dictionary. A package specification can exists without a package body but not vice versa. An element of a package, whether it is a variable or a module, can either be Public When defined in the specification a public element can be referenced from other programs and PL/SQL blocks Private When defined only in the body of the package, but does not appear in the specification. A private element cannot be referenced outside of the package. It can only be referenced by other elements within the package The sub-programs that are present inside a package cannot exist separately as database objects. A package cannot be called by itself. Only the procedures and functions from within the package can be called with reference to the package using the dot (.) operator. When one sub-program is called, then all other sub-programs are also loaded into the memory, hence the subsequent call for any other modules becomes fast.
Page 23 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Description Appends text from the procedure to the current line of the line output buffer Places an end_of_line marker in the output buffer Combines the action of PUT and NEW_LINE Retrieves the current line from the output buffer into the procedure Retrieves an array of lines from the output buffer into the procedure Enables or disables calls to the DBMS_OUTPUT procedures
Page 25 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 26 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Components of Triggers
The main components of Database Triggers are the following: Trigger Timing: It means when a trigger should fire. The possible trigger timing is BEFORE, AFTER and INSTEAD OF Trigger Event: The trigger event can be INSERT, UPDATE or DELETE Trigger Type: The type of trigger can be Statement or Row Trigger Body: This section specifies the action need to be performed by the trigger i.e. it is the PL/SQL block that gets executed
Page 27 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Types of Triggers
There are two kinds of triggers in Oracle: Row Level: o The action specified with the row level trigger will be executed for each affected row by the instruction for which the trigger is invoked o These triggers will fire for every INSERT/UPDATE/DELETE on the table depending on the number of rows affected by the triggering event o Should specify the keyword FOR EACH ROW Statement Level: o They get fired in the table level once for each trigger event o These triggers will fire for every INSERT/UPDATE/DELETE on the table irrespective of the number of rows affected by the triggering event o To define a statement level trigger omit the FOR EACH ROW keyword in the trigger specification
Create Triggers
Insert Triggers: BEFORE INSERT Trigger: A BEFORE INSERT Trigger means that Oracle will fire this trigger before the INSERT operation is executed. The syntax for a BEFORE INSERT Trigger is: CREATE or REPLACE TRIGGER trigger_name BEFORE INSERT ON TABLE [FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;
Page 28 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
[ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END; Update Triggers: BEFORE UPDATE Trigger: A BEFORE UPDATE Trigger means that Oracle will fire this trigger before the UPDATE operation is executed. The syntax for a BEFORE UPDATE Trigger is: CREATE or REPLACE TRIGGER trigger_name BEFORE UPDATE ON TABLE [ FOR EACH ROW ] DECLARE -- variable declarations BEGIN -- trigger code EXCEPTION WHEN ... -- exception handling END;
Page 29 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 30 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 31 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Summary
Triggers are stored procedures that gets implicitly executed when some database-related event occurs Can work for any DML statements like INSERT, UPDATE and DELETE but not for SELECT Triggers can be row level and statement level. The action specified with the row level trigger will be executed for each affected row by the instruction for which the trigger is invoked The statement level triggers will fire for every INSERT/UPDATE/DELETE on the table irrespective of the number of rows affected by the triggering event
Page 32 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Understand Cursors
A cursor is a mechanism by which you can assign a name to a "select statement" and manipulate the information within that SQL statement. In other words, a cursor is a SELECT statement that is defined within the declaration section of your PLSQL code. You will take a look at three different syntaxes for cursors. There are two types of cursors: Implicit and Explicit. An Implicit cursor is used for all other SQL statements. Implicit Cursors gives less programmatic control. In explicit cursor the cursor name is explicitly attached to a select statement The four PL/SQL steps necessary for explicit cursor processing are as follows: Declare the cursor Open the cursor Fetch the results into PL/SQL variables Close the cursor To use a cursor, it must be declared first. Syntax CURSOR cursor_name IS SELECT_statement; A cursor without parameters CURSOR comp IS SELECT compid FROM company; A cursor with parameters CURSOR comp (mcompid IN NUMBER) IS SELECT name FROM company WHERE compid = mcomid;
Page 33 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 34 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Fetch Cursor
The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so that some type of operation can be performed on the data. After declaring and opening your cursor, the next step is to FETCH the rows from your cursor. Fetching a cursor has two forms: FETCH cursor_name INTO list_of_variables; Or FETCH cursor_name INTO PL/SQL_record; After each FETCH, the active set pointer is increased to next row. Thus, each FETCH will return successive rows in the active set, until the entire set is returned. The %NOTFOUND attribute is used to determine when the active set has been retrieved. The basic syntax for a FETCH statement is: FETCH cursor_name INTO <list of variables>; For example, you could have a cursor defined as: CURSOR c1 IS SELECT course_number from courses_tbl where course_name = name_in; The command that would be used to fetch the data from this cursor is: FETCH c1 into cnumber; This would fetch the first course_number into the variable called cnumber;
Close Cursor
The final step of working with cursors is to close the cursor once you have finished using it. The basic syntax to CLOSE the cursor is: CLOSE cursor_name; For example, you could close a cursor called c1 with the following command: CLOSE c1;
Page 35 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
%NOTFOUND
%ROWCOUNT
Page 36 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 37 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
We've made this table definition very simple, for demonstration purposes. Step 2 - Create package Next, we've created a package called "winepkg" that contains our cursor definition. This needs to be done so that we can use a cursor as an output parameter in our stored procedure. create or replace PACKAGE winepkg IS /* Define the REF CURSOR type. */ TYPE wine_type IS REF CURSOR RETURN wine%ROWTYPE; END winepkg; This cursor will accept all fields from the "wine" table. Step 3 - Create stored procedure Our final step is to create a stored procedure to return the cursor. It accepts three parameters (entered by the user on the HTML Form) and returns a cursor (c1) of type "wine_type" which was declared in Step 2. The procedure will determine the appropriate cursor to return, based on the value(s) that have been entered by the user (input parameters). create or replace procedure find_wine2 (col1_in in varchar2, col2_in in varchar2, col3_in in varchar2, c1 out winepkg.wine_type) as BEGIN /* all columns were entered */ IF (length(col1_in) > 0) and (length(col2_in) > 0) and (length(col3_in) > 0) THEN OPEN c1 FOR select * from wine where wine.col1 = col1_in and wine.col2 = col2_in and wine.col3 = col3_in;
Page 38 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
> 0) and
= 0) and
> 0) and
= 0) and
> 0) and
= 0) and
Page 39 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 40 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Understanding Exceptions
What is an Exception? Exceptions are errors raised whenever there is any in a particular PL/SQL block. This causes a termination in the program by Oracle. Control then is transferred to the separate exception section of the program, if one exists, to handle the exception. Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL block and performs an illegal termination of the execution of the program. PL/SQL traps and responds to errors using architecture of exception handler. Occurrence of any error in PL/SQL, whether a system error or an application error, an exception is rose. This halts the processing in the current PL/SQL block's execution and control is transferred to the separate exception section of the program, if one exists, to handle the exception. The control never returns to that block after you finish handling the exception. Instead, control is passed to the enclosing block, if any.
Page 41 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Predefined Exceptions
Some exceptions are already defined in Oracle called the pre-defined exception. Mostly they are generated with the SELECT statement. They are raised implicitly at runtime. Every exception is associated with an error code. These exceptions are already defined in the STANDARD package (An Oracle supplied package). Oracle Exception Name DUP_VAL_ON_INDEX Oracle Error ORA-00001 Explanation You tried to execute an INSERT or UPDATE statement that has created a duplicate value in a field restricted by a unique index. You were waiting for a resource and you timed out. The remote portion of a transaction has rolled back. You tried to reference a cursor that does not yet exist. This may have happened because you have executed a FETCH cursor or CLOSE cursor before opening the cursor. You tried to execute a call to Oracle before logging in. You tried to log into Oracle with an invalid username or password combination. You tried one of the following: 1. You executed a SELECT INTO statement and no rows were returned. 2. You referenced an uninitialized row in a table. 3. You read past the end of file with the UTL_FILE package. You tried to execute a SELECT INTO statement and more than one row was returned. You tried to divide a number by zero.
TOO_MANY_ROWS ZERO_DIVIDE
ORA-01422 ORA-01476
Page 42 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 43 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
PRAGMA EXCEPTION_INIT
The pragma EXCEPTION_INIT associates an exception name with an Oracle error number. That lets you refer to any internal exception by name and to write a specific handler for it instead of using the OTHERS handler. Some uncommon predefined errors numbers exists that does have names. Oracle allows to associate a user-defined name with a predefined error number (Oracle Error).
Page 44 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
AS
RAISE_APPLICATION_ERROR
What is RAISE_APPLICATION_ERROR? The RAISE_APPLICATION_ERROR is a procedure that communicates application-specific errors from the server side (usually a database trigger) to the client-side application. This built-in procedure is the only mechanism available for communicating a server-side, programmer-defined exception to the client side in such a way that the client process can handle the exception. Error number should be of the range between 20000 and 20999. Error messages should be less than 512 characters. Syntax: RAISE_APPLICATION_ERROR (error_number in NUMBER, error_msg in VARCHAR2); Example: CREATE OR REPLACE PROCEDURE sp_addproduct( IN V_prdouct_code Varchar2(100); IN V_prdouct_name Varchar2(100);) BRGIN UPDATE product_dim SET product_name=V_prdouct_name
Page 45 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
AS
Summary
A SQL cursor is a private Oracle SQL working area. The implicit cursor is used by Oracle server to test and parse the SQL statements. Implicit cursors give less programmatic control. An implicit cursor is used for all other SQL statements. Explicit cursors are declared by the programmers. In explicit cursor the cursor name is explicitly attached to a select statement. Explicit cursor handling requires declaring, opening, fetching, and closing cursor. Oracle raises ERRORS whenever any abnormal situation arises in a PL/SQL block and performs an illegal termination of the execution of the program. PL/SQL traps and responds to errors using architecture of EXCEPTION handler. Pre-defined exceptions are already defined in the STANDARD package. Exceptions can be pre-defined (built-in) and user-defined.
11. Create a cursor to print empno, ename, job, sal, hiredate and the increment amount for all employees. Increment amount depends on the day of joining. Day of Joining Friday Wednesday Thursday For all others Increment in % 20 18 17 15
Page 46 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Introduction
Collections and records are composite types that have internal components that can be manipulated individually, such as the elements of an array, record or table.
Collection
A collection is a ordered group of elements, all of the same type. It is a general concept that encompasses list, arrays, and other familiar data types. Each element has a unique subscript that determines its position in the collection. Collections work like the arrays found in most third-generation programming language. A collection is a ordered group of elements, all of the same type. It is a general concept that encompasses list, arrays, and other familiar data types. Each element has a unique subscript that determines its position in the collection. Collections work like the arrays found in most third-generation programming language. PL/SQL has two collection types: tables and varrays. Tables comes in two flavours: o Index by tables (formerly called PL/SQL tables) o Nested tables
Index-by tables
Index-by tables: Also known as associative arrays. It lets you to look up elements using arbitrary numbers and strings for subscript values. Are similar to one-dimensional arrays and are referenced like arrays of records. Since index-by tables can be passed as parameters, they can be used to move columns of data into and out of database tables or between client-side applications and stored subprograms. Are composed of two components: o Primary key of data type BINARY_INTEGER o Column of scalar or record data type Can increase in size dynamically because they are unconstrained
Page 47 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 48 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
CREATE TYPE dependend_nt AS TABLE OF dependend_ty ; CREATE TABLE borrower (borrower_id NUMBER, borrowe_name VARCHAR2(50), borrower_adress VARCHAR2(100), dependends dependend_nt) NESTED TABLE dependends STORE AS dependend_nt_tab; INSERT INTO borrower (10001, 'JAMES', 'D2-14 ,CA 9264', dependend_nt(dependent_ty('JACOB','FATHER','31-MAR-1950'), dependent_ty('RUBELA','MOTHER','25-MAR-1949')));
SELECT borrower_name,N.dependend_name,N.realtionship, N.birth_date FROM borrower,TABLE(borrower.dependends) N ; SET DESCRIBE DEPTH 2 DESC borrower Difference between array and nested tables: First, arrays have a fixed upper bound, but nested tables are unbounded. So, the size of a nested table can increase dynamically. Second, arrays must be dense (have consecutive subscripts). So, individual elements cannot be deleted from an array. Initially, nested tables are dense, but they can be sparse (have non-consecutive subscripts).
Page 49 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Varrays
Items of type VARRAY are called varrays. Allow to associate a single identifier with an entire collection. Manipulate the collection as a whole and reference individual elements easily. To reference an element, use standard subscripting syntax. CREATE OR REPLACE TYPE addresses_va AS VARRAY(3) of VARCHAR2(50) ; CREATE TABLE borrower (borrower_id NUMBER, borrowe_name VARCHAR2(50), borrower_adress VARCHAR2(100), addresses addresses _VA); INSERT INTO borrower (10001, 'JAMES', 'D2-14 ,CA 9264', addresses_va('address1','address2','address3'));
SELECT addresses FROM borrower If you want to display the data from Varray in separates line then use TABLE function. SELECT b.borrower_name,n.* FROM borrower b,TABLE(b.addresses) N;
Collection method
FIRST: Returns the index of the first element in the collection. LAST: Returns the index of the last element in the collection. PRIOR(n): Returns the index of the element prior to the specified element. NEXT(n): Returns the index of the next element after the specified element. EXTEND: Appends a single null element to the collection. EXTEND(n): Appends n null elements to the collection. EXTEND(n1, n2): Appends n1 copies of the n2th element to the collection. TRIM: Removes a single element from the end of the collection. TRIM(n): Removes n elements from the end of the collection. DELETE: Removes all elements from the collection. DELETE(n): Removes element n from the collection. DELETE(n1,n2): Removes all elements from n1 to n2 from the collection.
Page 50 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Summary
A collection is an ordered group of elements, all of the same type. Each element has a unique subscript that determines its position in the collection. PL/SQL has two collection types: Tables and Varrays. Tables come in two flavours index-by tables (formerly called PL/SQL tables) and nested tables.
Page 51 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 52 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 54 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 55 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Summary
Dynamic SQL enables to write programs that reference SQL statement whose full text is not known until runtime. Dynamic SQL lets execute SQL statements that are not supported in static SQL Programs. The EXECUTE IMMEDIATE statement prepares (parses) and immediately executes a dynamic SQL statement or an anonymous PL/SQL block. BULK COLLECT and the FORALL statements allows to bulk together all of the context switches into a single switch and pass that to the SQL engine.
Page 56 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
6. The following are the two Dynamic SQL statements. What is the main difference between these two statements in the respect of execution? Begin EXECUTE IMMEDIATE 'CREATE TABLE X(A DATE)'; End; / CREATE OR REPLACE PROCEDURE CREATE_TABLE2 AS cur integer; rc integer; BEGIN cur := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cur, 'CREATE TABLE X (Y DATE)', DBMS_SQL.NATIVE); rc := DBMS_SQL.EXECUTE(cur); DBMS_SQL.CLOSE_CURSOR(cur); END;
Page 57 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Introduction
There are some utilities in Oracle that can be used to archive, load data into tables and backup / recover tables and database. The utilities that will be discussed here: Export Import SQL *Loader
Page 58 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 61 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Bad File
SQL *Loader
Datafile / s Oracle Database
Log File
SQL*Loader loads data from external files into tables in an Oracle DB. This utility is run at OS level and not from within SQLPLUS. Some features are as follows: Has a powerful data parsing engine which puts little limitation on the format of the data in the datafile. Can load data from multiple datafiles during the same load session. Can load data into multiple tables during the same load session. Is character set aware (you can specify the character set of the data). Can selectively load data (you can load records based on the records' values). Can manipulate the data before loading it, using SQL functions. Can generate unique sequential key values in specified columns. Can use the operating system's file system to access the datafile(s). Can load data from disk, tape, or named pipe. Does sophisticated error reporting which greatly aids troubleshooting. Supports two loading "paths" -- Conventional and Direct. Syntax $ sqlldr keyword=value [, keyword=value]
Page 62 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Summary
There are some utilities in Oracle that can be used to archive, load data into tables and backup / recover tables and database. The utilities that will be discussed here: Export Import SQL *Loader
Page 63 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
Page 64 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
References
Websites
http://otn.oracle.com http://www.docnmail.com/learn/Oracle.htm
Books
Oracle 10g Complete Reference: Kevin Loney, George Koch, Oracle Press
Page 65 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected
STUDENT NOTES:
Page 66 Copyright 2007, Cognizant Technology Solutions, All Rights Reserved C3: Protected