Using SQL in PL/SQL ITEC 224 Database Programming.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Chapter 4B: More Advanced PL/SQL Programming
Programming in Oracle with PL/SQL
Exception Handling in PL/SQL. POINTS TO DISCUSS What is Exception Handling Structure of Exception Handling Section Types of Exceptions.
PL/SQL Bulk Collections in Oracle 9i and 10g Kent Crotty Burleson Consulting October 13, 2006.
Bordoloi and Bock CURSORS. Bordoloi and Bock CURSOR MANIPULATION To process an SQL statement, ORACLE needs to create an area of memory known as the context.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Bordoloi and Bock EXCEPTIONS. Bordoloi and Bock Errors Two types of errors can be found in a program: compilation errors and runtime errors. There is.
Cursor and Exception Handling By Nidhi Bhatnagar.
Oracle10g Developer: PL/SQL Programming1 Objectives Manipulating data with cursors Managing errors with exception handlers Addressing exception-handling.
Chapter 4 Cursors and Exception Handling Oracle10g Developer:
Exceptions Oracle Database PL/SQL 10g Programming Chapter 7.
Program with PL/SQL. Interacting with the Oracle Server.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
1. 1. Which type of argument passes a value from a procedure to the calling program? A. VARCHAR2 B. BOOLEAN C. OUT D. IN 2.
L/O/G/O Working with Composite Data Types. Objectives After completing this lesson, you should be able to do the following: –Create user-defined PL/SQL.
CSIT 313 DB PROGRAMMING EXCEPTION HANDLING. In PL/SQL, an error condition is called an exception. An exception can be either –internally defined (by the.
1 CursorsCursors. 2 SQL Cursor A cursor is a private SQL work area. A cursor is a private SQL work area. There are two types of cursors: There are two.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
Trapping Oracle Server Exceptions. 2 home back first prev next last What Will I Learn? Describe and provide an example of an error defined by the Oracle.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Manipulating Data in PL/SQL. 2 home back first prev next last What Will I Learn? Construct and execute PL/SQL statements that manipulate data with DML.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
SQL Basics. What is SQL? SQL stands for Structured Query Language. SQL lets you access and manipulate databases.
Copyright  Oracle Corporation, All rights reserved. 18 Interacting with the Oracle Server.
Handling Exceptions. 2 home back first prev next last What Will I Learn? Describe several advantages of including exception handling code in PL/SQL Describe.
Oracle 8i Exception Handling. General Syntax DECLARE --- BEGIN --- EXCEPTION WHEN exception_name1 THEN -Error handling statements WHEN exception_name2.
© 2007 by Prentice Hall7-1 Introduction to Oracle 10g Chapter 7 Using PL/SQL to Your Advantage James Perry and Gerald Post.
Chapter Sixteen Cursors Objective: – Introduction to cursors – Use of cursors in a database record – Implicit & explicit cursors – Cursors & loops – Cursors.
PL/SQLPL/SQL Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
ITEC 224 Database Programming PL/SQL Lab Cursors.
1 Handling Exceptions Part F. 2 Handling Exceptions with PL/SQL What is an exception? Identifier in PL/SQL that is raised during execution What is an.
Chapter 16 Cursors and Exceptions. Chapter Objectives  Determine when an explicit cursor is required  Declare, open, and close an explicit cursor 
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
Retrieving Data in PL/SQL. 2 home back first prev next last What Will I Learn? In this lesson, you will learn to: –Recognize the SQL statements that can.
implicit and an explicit cursor
Chapter 18: Exception Handling1 Chapter Eighteen Exception Handling Objective: – Define exceptions – List types of exception handlers – Trap errors – Exception.
Handling Exceptions. Objectives What is exception Types of exceptions How to handle exceptions Trapping pre defined oracle errors.
1 PL/SQL Part C Scope and Interacting with the Oracle Server.
Copyright  Oracle Corporation, All rights reserved. 23 Handling Exceptions.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
Program with PL/SQL Lesson 3. Interacting with the Oracle Server.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
7 Copyright © 2004, Oracle. All rights reserved. Using Explicit Cursors.
ITEC 224 Database Programming
CS322: Database Systems PL/ SQL PL/SQL by Ivan Bayross.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
Interacting with the Oracle8 Server
Interacting with the Oracle Server
Programming in Oracle with PL/SQL
Interacting with the Oracle Server
Creating Stored Procedures and Functions
Interacting with the Oracle Server
SQL Stored Triggers Presented by: Dr. Samir Tartir
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Cursors ITEC 224 Database Programming PL/SQL Lab.
Oracle9i Developer: PL/SQL Programming Chapter 3 PL/SQL Processing.
Handling Exceptions.
SQL PL/SQL Presented by: Dr. Samir Tartir
Database Management Systems 2
Agenda Summary of last class Cursors Loops Records Simple Loops
Database Management Systems 2
Database Management Systems 2
Handling Exceptions.
Handling Exceptions.
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Cursors.
Database Management Systems 2
Handling Exceptions.
Presentation transcript:

Using SQL in PL/SQL ITEC 224 Database Programming

Cursors used for SQL statements Whenever an SQL command is executed in a PL/SQL block, Oracle assigns a private work area for that statement. Whenever an SQL command is executed in a PL/SQL block, Oracle assigns a private work area for that statement. This work area contains information about the SQL statement and the set of data returned or affected by that statement. This work area contains information about the SQL statement and the set of data returned or affected by that statement. There are two types of SQL cursor: There are two types of SQL cursor: implicit cursor. The implicit cursor is used by Oracle server to test and parse the SQL statements implicit cursor. The implicit cursor is used by Oracle server to test and parse the SQL statements explicit cursor : the explicit cursors are declared by the programmers. explicit cursor : the explicit cursors are declared by the programmers.

Attributes of Implicit Cursors Using the implicit cursor, we can test the outcome of SQL statements in PL/SQL blocks using the following attributes: Using the implicit cursor, we can test the outcome of SQL statements in PL/SQL blocks using the following attributes: SQL%ROWCOUNT: return the number of rows affected; SQL%ROWCOUNT: return the number of rows affected; SQL%FOUND : BOOLEAN attribute indicating whether the recent SQL statement matches to any row; SQL%FOUND : BOOLEAN attribute indicating whether the recent SQL statement matches to any row; SQL%NOTFOUND: BOOLEAN attribute indicating whether the recent SQL statement does not match to any row; SQL%NOTFOUND: BOOLEAN attribute indicating whether the recent SQL statement does not match to any row; SQL%ISOPEN: a BOOLEAN attribute and always evaluated as FALSE immediately after the SQL statement is executed. SQL%ISOPEN: a BOOLEAN attribute and always evaluated as FALSE immediately after the SQL statement is executed.

DML Commands DML commands (insert/delete/update) are used with no change inside any PL/SQL block DML commands (insert/delete/update) are used with no change inside any PL/SQL block Insert/delete/update commands modify the contents of the table and they do not really “return” any data. Insert/delete/update commands modify the contents of the table and they do not really “return” any data. It is possible to check the status of the statement using the implicit cursor attributes It is possible to check the status of the statement using the implicit cursor attributes

DML commands Task: Insert a new row into the following table: Author(AuthorId, Lname, FName) BEGIN INSERT INTO Author(AuthorId, Lname, FName) VALUES(‘5266’, ‘Armanfar’, ‘Hamed’); END;

DML commands Task: Append “old_” to the beginning of all last names BEGIN UPDATE Author SET lname = ‘old_’ || lname; DBMS_OUTPUT.PUT_LINE(SQL%rowcount || ’ names modified’); END;

Use of DML commands You can use as many DML commands as you need in one block You can use as many DML commands as you need in one block You should plan the DML commands and use the DCL commands commit or rollback in the appropriate places in your PL/SQL block. You should plan the DML commands and use the DCL commands commit or rollback in the appropriate places in your PL/SQL block.

Use of DML and DCL commands together Employees(employee_id, last_name, salary, department_id) Raises(department_id, number_modified) DECLARE v_dept_id number(4) :=&did; v_count number; BEGIN UPDATE employees SET salary = salary * 1.1 WHERE department_id = v_dept_id; IF SQL%FOUND THEN v_count := SQL%ROWCOUNT; INSERT INTO raises VALUES(v_dept_id, v_count); COMMIT; ELSE ROLLBACK; END IF; END; Task: Increase salary of all employees in a given department by 10%. Read the department id from the keyboard. If any rows were updated, insert a new row into the raises table containing the department id of the specified department and the number of rows modified and commit. Otherwise undo the update. Use the following tables: Employees.department_id%TYPE Anchored declaration may be used here. v_dept_id has the same data type as the department_id column of the employees table SQL%ROWCOUNT>0 Alternatively, rowcount may be used as part of the conditionIf the update command did not find any rows, t means rowcount=0.

Use of SELECT in PL/SQL blocks Select statement returns a set of results and these results are normally displayed on screen Select statement returns a set of results and these results are normally displayed on screen When used inside a PL/SQL block, the results returned by the SELECT statement must be saved into variables therefore SELECT INTO statement is used When used inside a PL/SQL block, the results returned by the SELECT statement must be saved into variables therefore SELECT INTO statement is used Syntax of Select Into : Syntax of Select Into : SELECT INTO FROM WHERE GROUP BY HAVING ORDER BY

Example Select Into Task: Print on screen the average salary of all employees DECLARE v_avg_salaryemployees.salary%TYPE; BEGIN SELECT avg(salary) INTO v_avg_salary FROM employees; DBMS_OUTPUT.PUT_LINE( ‘The average salary of all employees is ’ ||v_avg_salary); END; The average salary of all employees is Employees(employee_id, last_name, salary, department_id)

Example Select Into Task: Print on screen names of employees in the employees table. DECLARE v_nameemployees.last_name%TYPE; BEGIN SELECT last_name INTO v_name FROM employees; DBMS_OUTPUT.PUT_LINE( ‘Employee name is ’ ||v_name); END; DECLARE * ERROR at line 1: ORA-01422: exact fetch returns more than requested number of rows ORA-06512: at line 4 If select into returns more than one row, an exception (error) is raised and the program crashes. Employees(employee_id, last_name, salary, department_id)

Example Select Into Task: Print on screen name of employees in department 99 DECLARE v_nameemployees.last_name%TYPE; BEGIN SELECT last_name INTO v_name FROM employees; WHERE department_id = 99; DBMS_OUTPUT.PUT_LINE( ‘Employee name is ’||v_name); END; DECLARE * ERROR at line 1: ORA-01403: no data found ORA-06512: at line 4 If select into returns no rows, an exception (error) is raised and the program crashes.

Handling Select Into exceptions NO_DATA_FOUND : A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index- by table. NO_DATA_FOUND : A SELECT INTO statement returns no rows, or your program references a deleted element in a nested table or an uninitialized element in an index- by table. TOO_MANY_ROWS : A SELECT INTO statement returns more than one row.VALUE_ERRORAn arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL aborts the assignment and raises TOO_MANY_ROWS : A SELECT INTO statement returns more than one row.VALUE_ERRORAn arithmetic, conversion, truncation, or size-constraint error occurs. For example, when your program selects a column value into a character variable, if the value is longer than the declared length of the variable, PL/SQL aborts the assignment and raises VALUE_ERROR. In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails. VALUE_ERROR. In procedural statements, VALUE_ERROR is raised if the conversion of a character string into a number fails.

DML related Exceptions Oracle Exception Name Oracle Error Number Description NO_DATA_FOUNDORA SELECT INTO statement returns no rows TOO_MANY_ROWSORA SELECT INTO statement returns more than one row. VALUE_ERRORORA An arithmetic, conversion, truncation, or size-constraint error occurs ZERO_DIVIDEORA Attempt to divide a number by zero. DUP_VAL_ON_INDEXORA Uniqueness of a column is violated by INSERT or UPDATE Every error that can be detected by Oracle has a unique number. Some exceptions have pre-defined names associated with them.

Handling exceptions of Select Into DECLARE v_name employees.last_name%TYPE; v_deptid employees.department_id%TYPE := &dept_id BEGIN SELECT last_name INTO v_name FROM employees; WHERE department_id = v_deptid; DBMS_OUTPUT.PUT_LINE( ‘Employee name is ’||v_name); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE(‘ More than one row’); WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(‘ No data’); END; Enter value for dept_id: 99 old 3: v_deptid employees.department_id%TYPE := &dept_id new 3: v_deptid employees.department_id%TYPE := 99 No data PL/SQL procedure successfully completed. There are no employees in department 99 Exception handling section

Handling exceptions of Select Into DECLARE v_name employees.last_name%TYPE; v_deptid employees.department_id%TYPE := &dept_id BEGIN SELECT last_name INTO v_name FROM employees; WHERE department_id = v_deptid; DBMS_OUTPUT.PUT_LINE( ‘Employee name is ’||v_name); EXCEPTION WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE(‘ More than one row’); WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(‘ No data’); END; Enter value for dept_id: 20 old 3: v_deptid employees.department_id%TYPE := &dept_id new 3: v_deptid employees.department_id%TYPE := 20 More than one row PL/SQL procedure successfully completed. There are two employees in department 20 Exception handling section

Handling exceptions of Select Into DECLARE v_name number; v_deptid employees.department_id%TYPE := &dept_id BEGIN SELECT last_name INTO v_name FROM employees; WHERE department_id = v_deptid; DBMS_OUTPUT.PUT_LINE( ‘Employee name is ’||v_name); EXCEPTION WHEN VALUE_ERROR THEN DBMS_OUTPUT.PUT_LINE(‘Data type conversion problem’); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(‘error’); END; Enter value for dept_id: 10 old 3: v_deptid employees.department_id%TYPE := &dept_id new 3: v_deptid employees.department_id%TYPE := 10 Data type conversion problem PL/SQL procedure successfully completed. There is only one employee in department 10 OTHERS is a catch-all phrase for exceptions

SELECT INTO CAN HANDLE ONLY A SINGLE ROW

Handling exceptions of Select Into DECLARE v_name varchar2(2); v_deptid employees.department_id%TYPE := &dept_id BEGIN SELECT last_name INTO v_name FROM employees; WHERE department_id = v_deptid; DBMS_OUTPUT.PUT_LINE( ‘Employee name is ’||v_name); EXCEPTION WHEN VALUE_ERROR THEN DBMS_OUTPUT.PUT_LINE(‘Data type conversion problem’); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(‘error’); END; Enter value for dept_id: 10 old 3: v_deptid employees.department_id%TYPE := &dept_id new 3: v_deptid employees.department_id%TYPE := 10 Data type conversion problem PL/SQL procedure successfully completed. There is only one employee in department 10 and his last name is Whalen OTHERS is a catch-all phrase for exceptions

Handling exceptions of DML statements BEGIN INSERT INTO regions (region_id, region_name) VALUES(1, ‘SCT’); EXCEPTION WHEN DUP_VAL_ON_INDEX THEN DBMS_OUTPUT.PUT_LINE(‘Region_id must be unique’); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(‘Error’); END; Region_id must be unique PL/SQL procedure successfully completed. Region_id is the Primary key of regions table and therefore must be unique. Region_id=1 already exists in the table

You should anticipate all possible problems and handle them in the exception handling section

Summary This week we covered Cursors Cursors Cursor Attributes Cursor Attributes How to use DML commands in PL/SQL blocks How to use DML commands in PL/SQL blocks How to use select INTO in PL/SQL blocks How to use select INTO in PL/SQL blocks Handling exceptions related to SELECT INTO and DMLcommands Handling exceptions related to SELECT INTO and DMLcommands Next Week we will learn about the explicit cursors