Distributed Database Applications COSC 5050 Week Three.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
PL/SQL. Introduction to PL/SQL PL/SQL is the procedure extension to Oracle SQL. It is used to access an Oracle database from various environments (e.g.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Advanced Package Concepts. 2 home back first prev next last What Will I Learn? Write packages that use the overloading feature Write packages that use.
1 Copyright © 2004, Oracle. All rights reserved. Creating Stored Procedures.
PL/SQL Agenda: Basic PL/SQL block structure
Oracle PL/SQL Eyad Husni Elshami. Why PL/SQL Block Structures: – PL/SQL consists of blocks of code, which can be nested within each other. Each block.
Programming in Oracle with PL/SQL
Matthew P. Johnson, OCL2, CISDD CUNY, January OCL2 Oracle 10g: SQL & PL/SQL Session #8 Matthew P. Johnson CISDD, CUNY Fall, 2004.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
Introduction to PL/SQL. Procedural Language extension for SQL Oracle Proprietary 3GL Capabilities Integration of SQL Portable within Oracle data bases.
Advanced Databases Advanced PL/SQL Programming: Procedure, Function and Package.
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.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
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:
Lecture 4 PL/SQL language. PL/SQL – procedural SQL Allows combining procedural and SQL code PL/SQL code is compiled, including SQL commands PL/SQL code.
Oracle Sequences Sequences are an independent object in the database (not a data type) Sequences have a name and can be used anywhere a value is expected.
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.
Distributed Database Applications COSC 5050 Week One.
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.
PL/SQL Cursors Session - II. Attributes Attributes %TYPE %ROWTYPE % Found % NotFound % RowCount % IsOPen %TYPE %ROWTYPE % Found % NotFound % RowCount.
PL SQL Block Structures. What is PL SQL A good way to get acquainted with PL/SQL is to look at a sample program. PL/SQL combines the data manipulating.
Advanced SQL: Cursors & Stored Procedures
Matthew P. Johnson, OCL3, CISDD CUNY, June OCL3 Oracle 10g: SQL & PL/SQL Session #8 Matthew P. Johnson CISDD, CUNY June, 2004.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
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.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Distributed Database Applications COSC 5050 Week Five.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
Using SQL in PL/SQL ITEC 224 Database Programming.
Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
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.
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.
implicit and an explicit cursor
Distributed Database Applications COSC 5050 Week Six.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
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.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
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.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
PLSQL Cont…. Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length.
ITEC 224 Database Programming
CS322: Database Systems PL/ SQL PL/SQL by Ivan Bayross.
Programming in Oracle with PL/SQL
Interacting with the Oracle Server
Creating Stored Procedures and Functions
Interacting with the Oracle Server
Oracle11g: PL/SQL Programming Chapter 4 Cursors and Exception Handling.
Cursors ITEC 224 Database Programming PL/SQL Lab.
SQL PL/SQL Presented by: Dr. Samir Tartir
Chapter Eighteen Cursors
Database Management Systems 2
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
Cursors.
Chapter 8 Advanced SQL Pearson Education © 2009.
Presentation transcript:

Distributed Database Applications COSC 5050 Week Three

Jiangping Wang Distributed Database Applications Outline Cursors and data retrieval Procedures Functions Parameters Sequences

Jiangping Wang Distributed Database Applications Cursors and Data Retrieval PL/SQL integrates with the Oracle database System Global Area (SGA) Private working area for SQL statement Cursor To query data from the database and make that data available within PL/SQL programs Implicit cursor Explicit cursor Cursor variable

Jiangping Wang Distributed Database Applications Cursor Cursor is a pointer into a virtual table in the database CURSOR employee_cur IS SELECT fname, lname FROM employee; OPEN employee_cur; FETCH employee_cur INTO employee_rec; CLOSE employee_cur;

Jiangping Wang Distributed Database Applications Cursor Fetch Operation

Jiangping Wang Distributed Database Applications Cursor create or replace procedure cursor_employee is CURSOR employee_cur IS SELECT fname, lname FROM employee WHERE ssn = ' '; employee_rec employee_cur%rowtype; begin OPEN employee_cur; FETCH employee_cur INTO employee_rec; dbms_output.put_line( employee_rec.fname || ' ' ||employee_rec.lname); CLOSE employee_cur; end; /

Jiangping Wang Distributed Database Applications Cursor Attributes Page 468 %FOUND Status of fetch operation True if fetch succeeded %NOTFOUND Opposite of %FOUND %ROWCOUNT Number of records fetched %ISOPEN True if the cursor is open cursor_name%attribute_name

Jiangping Wang Distributed Database Applications Referencing Variables in Cursor Identifier precedence in a cursor Qualifying variable with proc name Using standard naming conventions create or replace PROCEDURE adjust IS l_code NUMBER := 1000; CURSOR double_code_cur IS SELECT code + l_code as adjusted FROM employee WHERE dept_num = 2; employee_rec double_code_cur%rowtype; begin OPEN double_code_cur; FETCH double_code_cur INTO employee_rec; dbms_output.put_line(employee_rec.adjusted); CLOSE double_code_cur; END;

Jiangping Wang Distributed Database Applications Implicit Cursor Use SELECT INTO DECLARE l_department department.dept_name%TYPE; BEGIN SELECT dept_name INTO l_department FROM department WHERE dept_num = 1; DBMS_OUTPUT.PUT_LINE(l_department); END; DECLARE l_department department%ROWTYPE; BEGIN SELECT * INTO l_department FROM department WHERE dept_num = 1; DBMS_OUTPUT.PUT_LINE(l_department.dept_name); END;

Jiangping Wang Distributed Database Applications Implicit Cursor DECLARE l_department department%ROWTYPE; BEGIN SELECT * INTO l_department FROM department WHERE dept_num = 3; DBMS_OUTPUT.PUT_LINE(l_department.dept_name); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('No data!'); WHEN TOO_MANY_ROWS THEN DBMS_OUTPUT.PUT_LINE('Too many rows'); END; / Implicit SQL cursor attributes SQL%FOUND SQL%NOTFOUND SQL%ROWCOUNT SQL%ISOPEN Error handling With exception

Jiangping Wang Distributed Database Applications Explicit Cursor Explicitly defined in declaration section Complete control over open, fetch, close CURSOR company_cur IS SELECT company_id FROM company; CURSOR name_cur (company_id_in IN NUMBER) IS SELECT name FROM company WHERE company_id = company_id_in; CURSOR emp_cur RETURN employee%ROWTYPE IS SELECT * FROM employee WHERE department_id = 10;

Jiangping Wang Distributed Database Applications Explicit Cursor Open Fetch Close Explicit cursor attributes cursor%FOUND cursor%NOTFOUND cursor%ROWCOUNT cursor%ISOPEN

Jiangping Wang Distributed Database Applications Explicit Cursor DECLARE CURSOR c1 IS SELECT fname, lname, code, code*1.1 new_code FROM employee; rec c1%ROWTYPE; BEGIN OPEN c1; LOOP FETCH c1 INTO rec; EXIT WHEN c1%NOTFOUND; DBMS_OUTPUT.PUT_LINE( rec.fname || ' ' || rec.lname || ' ' || rec.code || ' ' || rec.new_code); END LOOP; CLOSE c1; END; /

Jiangping Wang Distributed Database Applications Explicit Cursor DECLARE l_dept_id NUMBER := 1; CURSOR name_cur (dept_id_in IN NUMBER) IS SELECT dept_name, lname FROM department inner join employee on department.dept_mgr_ssn = employee.ssn WHERE department.dept_num = dept_id_in; name_rec name_cur%ROWTYPE; BEGIN OPEN name_cur(l_dept_id); LOOP FETCH name_cur INTO name_rec; EXIT WHEN name_cur%NOTFOUND; DBMS_OUTPUT.PUT_LINE( name_rec.dept_name || ' ' || name_rec.lname); END LOOP; CLOSE name_cur; END; /

Jiangping Wang Distributed Database Applications Explicit Cursor DECLARE CURSOR emp_cur RETURN employee%rowtype IS SELECT * FROM employee WHERE dept_num = 15; emp_rec emp_cur%ROWTYPE; BEGIN OPEN emp_cur; LOOP FETCH emp_cur INTO emp_rec; EXIT WHEN emp_cur%NOTFOUND; DBMS_OUTPUT.PUT_LINE(emp_cur%rowcount || ': ' || emp_rec.fname || ' ' || emp_rec.lname); END LOOP; CLOSE emp_cur; END; /

Jiangping Wang Distributed Database Applications Cursor Variable Cursor variable points to or references an underlying cursor DECLARE TYPE employee_curtype IS REF CURSOR RETURN employee%ROWTYPE; employee_curvar employee_curtype; employee_rec employee%ROWTYPE; BEGIN OPEN employee_curvar FOR SELECT * FROM employee; FETCH employee_curvar INTO employee_rec; CLOSE employee_curvar; dbms_output.put_line(employee_rec.fname); END; /

Jiangping Wang Distributed Database Applications Cursor Loop Cursor with simple loop DECLARE CURSOR name_cur IS SELECT lname, fname FROM employee WHERE ssn like '8%'; name_rec name_cur%ROWTYPE; BEGIN OPEN name_cur; LOOP FETCH name_cur INTO name_rec; EXIT WHEN name_cur%NOTFOUND; DBMS_OUTPUT.PUT_LINE( name_rec.fname || ' ' || name_rec.lname); END LOOP; CLOSE name_cur; END; /

Jiangping Wang Distributed Database Applications Cursor Loop Cursor with simple loop DECLARE CURSOR occupancy_cur IS SELECT pet_id, room_number FROM occupancy WHERE occupied_dt = TRUNC(SYSDATE); occupancy_rec occupancy_cur%ROWTYPE; BEGIN OPEN occupancy_cur; LOOP FETCH occupancy_cur INTO occupancy_rec; EXIT WHEN occupancy_cur%NOTFOUND; update_bill (occupancy_rec.pet_id, occupancy_rec.room_number); END LOOP; CLOSE occupancy_cur; END;

Jiangping Wang Distributed Database Applications Cursor FOR Loop Cursor For loop DECLARE CURSOR occupancy_cur IS SELECT pet_id, room_number FROM occupancy WHERE occupied_dt = TRUNC(SYSDATE); BEGIN FOR occupancy_rec IN occupancy_cur LOOP update_bill (occupancy_rec.pet_id, occupancy_rec.room_number); END LOOP; END;

Jiangping Wang Distributed Database Applications Cursor FOR Loop Cursor FOR loop DECLARE CURSOR name_cur IS SELECT lname, fname FROM employee WHERE ssn like '8%'; BEGIN FOR name_rec IN name_cur LOOP DBMS_OUTPUT.PUT_LINE( name_rec.fname || ' ' || name_rec.lname); END LOOP; END; /

Jiangping Wang Distributed Database Applications Modular Code PL/SQL offers the following structures that modularize your code in different ways Procedure Function Trigger Package

Jiangping Wang Distributed Database Applications Procedure Procedure is a module that performs one or more actions Can be a standalone call, executable statement

Jiangping Wang Distributed Database Applications Procedure CREATE OR REPLACE PROCEDURE get_happy (ename_in IN VARCHAR2)  Header IS hiredate DATE;  Declarations BEGIN hiredate:= SYSDATE – 2; INSERT INTO employee (emp_name, hiredate) VALUES (ename_in, hiredate);  Code Body EXCEPTION* optional * WHEN DUP_VAL_IN_INDEX THEN DBMS_OUTPUT.PUT_LINE (‘Cannot insert.’);  Exception block * optional * END get_happy;

Jiangping Wang Procedure Distributed Database Applications

Jiangping Wang Distributed Database Applications Procedure procedure Add_employee (ssninvarchar2, fnameinvarchar2, lnameinvarchar2, dept_numinnumber, codeinnumber, sup_ssn invarchar2) is begin insert into employee values (ssn, fname, lname, dept_num, code, sup_ssn); end;

Jiangping Wang Distributed Database Applications Procedure procedure delete_employee (tgt_ssn in varchar2) is cursor dept_mgr_cur (tst_ssn varchar2) is select dept_mgr_ssn from department where dept_mgr_ssn = tst_ssn; dept_mgr_cur_ssn varchar2(9); begin open dept_mgr_cur(tgt_ssn); fetch dept_mgr_cur into dept_mgr_cur_ssn; if (dept_mgr_cur%found) then update department set dept_mgr_ssn = NULL where dept_mgr_ssn = tgt_ssn; end if; delete from employee where ssn = tgt_ssn; close dept_mgr_cur; end;

Jiangping Wang Distributed Database Applications Procedure Calling a procedure Procedure is called as an executable PL/SQL statement Called in a block Must end with (;) begin apply_discount( new_company_id, 0.15 ); display_store_summary; display_store_summary(); end;

Jiangping Wang Distributed Database Applications Function Function is a module that returns a value Function can exist only as part of an executable statement Function has a datatype

Jiangping Wang Distributed Database Applications Function CREATE OR REPLACE FUNCTION soft_pillow (type_in IN VARCHAR2) RETURN BOOLEAN  Header IS CURSOR pillow_cur (type_in pillow.pillow_type%TYPE) IS SELECT softness FROM pillow WHERE pillow_type = type-in; Pillow_rec pillow_cur%ROWTYPE;  Declarations BEGIN OPEN pillow_cur(type_in); FETCH pillow_cur INTO Pillow_rec; CLOSE pillow_cur; RETURN Pillow_rec.softness;  Code Body EXCEPTION* optional *  Exception block * optional * END soft_pillow;

Jiangping Wang Function Distributed Database Applications

Jiangping Wang Distributed Database Applications Function Defining function create or replace function favorite_nickname( name_in in varchar2) return varchar2 is begin End; Calling function declare nickname varchar2(100) := favorite_nickname(‘Nic’);

Jiangping Wang Distributed Database Applications Function create or replace function get_department( ssn_in in employee.ssn%type) return department.dept_name%type is l_dept_name department.dept_name%type; begin select dept_name into l_dept_name from department inner join employee on employee.dept_num = department.dept_num where ssn = ssn_in; dbms_output.put_line('department name: ' || l_dept_name); return l_dept_name; exception when no_data_found then dbms_output.put_line( 'no such employee or not in any department!'); return null; end; /

Jiangping Wang Distributed Database Applications Parameter Be used to pass information back and forth Parameter declaration must be unconstrained DECLARE company_name varchar2(60); PROCEDURE display_company( company_name IN varchar2) IS …

Jiangping Wang Distributed Database Applications Parameter Mode IN mode: Read-only Is the default mode Value cannot be changed Can have default value Passed by reference OUT mode: Write-only Has no value until the end No default value Actual parameter must be a variable Passed by value IN OUT mode: Read-write Cannot have default value Must be a variable Passed by value

Jiangping Wang Distributed Database Applications Parameter create or replace procedure delete_employee ( tgt_ssn_in in varchar2, removed_name_out out varchar2) is cursor dept_mgr_cur (tst_ssn varchar2) is select dept_mgr_ssn from department where dept_mgr_ssn = tst_ssn; dept_mgr_cur_ssn varchar2(9); begin open dept_mgr_cur(tgt_ssn_in); fetch dept_mgr_cur into dept_mgr_cur_ssn; if (dept_mgr_cur%found) then update department set dept_mgr_ssn = NULL where dept_mgr_ssn = tgt_ssn_in; end if; select lname into removed_name_out from employee where ssn = tgt_ssn_in; delete from employee where ssn = tgt_ssn_in; close dept_mgr_cur; end; /

Jiangping Wang Parameter Distributed Database Applications create or replace PROCEDURE combine_and_format_names (first_name_inout IN OUT VARCHAR2, last_name_inout IN OUT VARCHAR2, full_name_out OUT VARCHAR2, name_format_in IN VARCHAR2 := 'LAST, FIRST') IS BEGIN first_name_inout := UPPER (first_name_inout); last_name_inout := UPPER (last_name_inout); IF name_format_in = 'LAST, FIRST' THEN full_name_out := last_name_inout || ', ' || first_name_inout; ELSIF name_format_in = 'FIRST LAST' THEN full_name_out := first_name_inout || ' ' || last_name_inout; END IF; END; /

Jiangping Wang Distributed Database Applications Oracle Sequences Independent object in the database Not a data type Not tied to a table or a column Can be used anywhere a value is expected Generate a numeric value that can be assigned to any column in any table The table attribute to which you assigned a value based on a sequence can be edited and modified Can be created and deleted anytime

Jiangping Wang Distributed Database Applications Oracle Sequences CREATE SEQUENCE NAME [START WITH N] [INCREMENT BY N] [CACHE | NOCACHE] CREATE SEQUENCE CUS_CODE_SEQ START WITH NOCACHE; CREATE SEQUENCE INV_NUMBER_SEQ START WITH 4010 NOCACHE; SELECT * FROM USER_SEQUENCES; DROP SEQUENCE CUS_CODE_SEQ; DROP SEQUENCE INV_NUMBER_SEQ;

Jiangping Wang Distributed Database Applications Oracle Sequences INSERT INTO CUSTOMER VALUES (CUS_CODE_SEQ.NEXTVAL, ‘CONNERY’, ‘SEAN’, NULL, ‘615’, ‘ ’, 0.00); INSERT INTO INVOICE VALUES (INV_NUMBER_SEQ.NEXTVAL, 20010, SYSDATE); INSERT INTO LINE VALUES (INV_NUMBER_SEQ.CURRVAL, 1, ‘13-Q2/P2’, 1, 14.99); INSERT INTO LINE VALUES (INV_NUMBER_SEQ.CURRVAL, 2, ‘23109-HB’, 1, 9.95);

Jiangping Wang Distributed Database Applications Oracle Sequences Once a sequence value is used (through NEXTVAL), it cannot be used again If SQL statement rolls back, the sequence value does not roll back A sequence is not associated with a table A sequence can be used to generate unique values for more than one tables Dropping a sequence does not delete the values generated A sequence has one purpose: assign unique numbers to stuff Do not expect a sequence to return gap free values

Jiangping Wang Distributed Database Applications Homework Create a function that returns the next available customer ID. Create a stored procedure that accepts customer data as input arguments, adds a new customer record to the customer table. Create a stored procedure that accepts a numeric amount as an input argument that will be used as a filter threshold and prints a listing of customer information. Lab activities