PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]

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.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
Stored Procedure Language Stored Procedure Overview Stored Procedure is a function in a shared library accessible to the database server can also write.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
Chapter 4B: More Advanced PL/SQL Programming
A Guide to Oracle9i1 Advanced SQL And PL/SQL Topics Chapter 9.
PL/SQL Agenda: Basic PL/SQL block structure
Programming in Oracle with PL/SQL
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
Chapter 7 Managing Data Sources. ASP.NET 2.0, Third Edition2.
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Copyright  Oracle Corporation, All rights reserved. 4 Creating Functions.
1 PL/SQL programming Procedures and Cursors Lecture 1 Akhtar Ali.
Cursors in Pl/SQL Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
PL/SQL Bulk Collections in Oracle 9i and 10g Kent Crotty Burleson Consulting October 13, 2006.
ORACLE ONLINE TRAINING Contact our Support Team : SOFTNSOL India: Skype id : softnsoltrainings id:
Session Title: Using SQL and PL/SQL for Queries and Reporting Presented By: Stephen Frederic Institution: IHL September 16, 2013.
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.
Distributed Database Applications COSC 5050 Week Three.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Lecture 4 Introduction to PL/SQL Procedures & Cursors.
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.
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.
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
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
Managing users and security Akhtar Ali. Aims Understand and manage profiles Understand and manage users Understand and manage privileges Understand and.
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.
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.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
Commercial RDBMSs Access and Oracle. Access DBMS Architchecture  Can be used as a standalone system on a single PC: -JET Engine -Microsoft Data Engine.
School of Computing and Management Sciences © Sheffield Hallam University SQL is non-procedural –designed to be relatively approachable to non- programmers.
Advanced SQL: Triggers & Assertions
Stored Procedures. Definition a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database.
What is a Package? A package is an Oracle object, which holds other objects within it. Objects commonly held within a package are procedures, functions,
Objectives Database triggers and syntax
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 9 Database Triggers.
Using SQL in PL/SQL ITEC 224 Database Programming.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
ITEC 224 Database Programming PL/SQL Lab Cursors.
Dynamic SQL. 2 home back first prev next last What Will I Learn? Recall the stages through which all SQL statements pass Describe the reasons for using.
Introduction to Explicit Cursors. 2 home back first prev next last What Will I Learn? Distinguish between an implicit and an explicit cursor Describe.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
implicit and an explicit cursor
Learningcomputer.com SQL Server 2008 –Views, Functions and Stored Procedures.
A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows: CREATE.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
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.
What Are Subprograms? Subprograms are named PL/SQL blocks that can take parameters and be invoked. Subprograms allow decomposition of a program into logical.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
A Guide to SQL, Seventh Edition
Creating Stored Procedures and Functions
PL/SQL.
REF Cursors.
ORACLE SQL Developer & SQLPLUS Statements
PRACTICE OVERVIEW PL/SQL Part - 2.
Introduction to PL/SQL Procedures & Cursors
Advanced SQL: Views & Triggers
PRACTICE OVERVIEW PL/SQL Part - 1.
Chapter 8 Advanced SQL.
Chapter 8 Advanced SQL Pearson Education © 2009.
Stored Procedure Language
Presentation transcript:

PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]

SQL refresher Basic commands SELECT, INSERT, DELETE, UPDATE Always remember to state the table(s) you are selecting data from Join tables by primary and foreign keys Filter data using WHERE clause SELECT... FROM... [WHERE...]

SQL scripts Set of commands to run in sequence. Stored in a ‘note pad’ not data dictionary and accessed by file name Executed command Script called: Create_lecturer_copy.sql Executed by:

The SQL Procedure Block of SQL statements stored in the Data dictionary and called by applications Satisfies frequently-used or critical application logic When called all code within the procedure is executed (unlike packages) Action takes place on server not client Does not return value to calling program Not available in Oracle 6 or older Aids security as DBA may grant access to procedures not tables, therefore some users cannot access tables except through a procedure

Building a procedure: contents 1. Create or replace command 2. Object to be created 3. Name of object 4. Any variables accessed or imported 5. Local variables declared 6. Code 7. End procedure declaration

1. Create or replace command 2. Object to be created 3. Name of object 4. Any variables accessed or imported 5. Declared local variables 6. Code 7. End procedure declaration Create or replace procedure inflation_rise (inf_rate in number) Begin update employee set salary = salary + (salary * inf_rate / 100); commit; End; This procedure is called inflation_rise and uses a variable accessed as inf_rate which is a number, this is passed in when the procedure is used. It simply updates the salary by the rate of inflation.

Compiling and executing procedures Like any program the code needs to be compiles the procedure in a file with this name makes it available to the database Execute inflation_rise executes the procedure. Remember to compile a procedure again once it has been amended. For ease of use, it is best to write procedures in notepad and then run them, this means that they can be easily edited and you have a backup copy

Example Create or replace procedure validate_customer (v_cust in varchar2(10)) as Countnumber; Begin count = select count(*) from customer where cust_code = v_cust; if count > 0 then dbms.output ‘customer valid’; else dbms.output ‘customer not recognised’; end if; End; Any variables passed into procedure Local variables used by procedure SQL

Cursors in SQL Enable users to loop around a set of data. Store data selected from a query in a temp area for use when opened. Useful in complex actions which would not be feasible in standard SQL selection queries Cursor attributes - %notfound, %rowcount, %found & %isopen

Syntax for Cursors Declared as a variable in the same way as standard variables Identified as cursor type SQL retrieval set is included e.g. Cursor cur_emp is Select emp_id, surname ‘name’, grade, salary From employee Where regrade is true;

Cursor Population The data is populated when the cursor is opened. Once opened the data must be moved from the temp area to a local variable to be used by the program. These variables must be populated in the same order that the data is held in the cursor. The cursor data is looped around until an exit clause is reached.

THE JELLY BABY DEMO! Data has been selected from the employee table. This data needs to be amended in the following way: Each member of staff is to be increased one grade. Each member of staff is to have a £500 pay rise If the pay rise does not take them to the minimum for their new grade they are to be increased to the minimum for that grade If the pay rise moves them above the maximum for a grade they are to be increased to the maximum only

Create or replace procedure proc_test as v_empidnumber; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; loop fetch cur_sample into v_empid; exit when cur_sample%notfound update employee set salary = salary where empid = v_empid; end loop; End; Open cursor for use Loops round each value returned by the cursor Places the value from the cursor into the variable v_empid Stop when no more records are found Data returned by cursor Declare Cursor

Using cursors DECLARE, OPEN, LOOP & FETCH Declare V_empidnumber; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; loop fetch cur_sample into v_empid; exit when cur_sample%notfound update employee set salary = salary where empid = v_empid; end loop; End; Loops round each value returned by the select statement and updates the salary accordingly

Loops and cursors Loop – exit Declare V_empidnumber; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; loop fetch cur_sample into v_empid; exit when cur_sample%notfound update employee set salary = salary where empid = v_empid; end loop; End; This is the simplest type of loop. Exit will indicate the criteria for the loop to drop out

While - loop Declare V_empidnumber; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; fetch cur_sample into v_empid; while cur_sample%found loop update employee set salary = salary where empid = v_empid; end loop; End; Will loop around as long as %found returns a true value Loops and cursors continued

for - loop Declare V_empidnumber; V_countnumber :=1; V_maxnumber; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; v_max :=cur_sample%rowcount fetch cur_sample into v_empid; for v_count in 1.. V_max loop update employee set salary = salary where empid = v_empid; v_count := v_count + 1; end loop; End; Declare the additional variables required Will loop around as long as v_count is not greater than the number of rows returned Remember to increment the value of v_count

Placing cursors into procedures Creation command Variable declarations Body of code Create or replace procedure sample1 as v_deptname varchar2(10); v_deptid number cursor cur_deptchange is select distinct deptid, deptname from dept; BEGIN open cur_deptchange; fetch cur_dept into v_deptid, v_deptname; loop exit when cur_deptchange%notfound update employee set emp_deptname = v_deptname where emp_deptid = v_deptid; commit; end loop; END;

Notepad file called: Create_procedures.sql 1) Open SQL*Plus and logon 2) At the prompt You will get a prompt which should say ‘procedure created’ 3) To run the procedure enter: Execute proc_test 4) If you check your data you should now find that the procedure has run successfully

Use of conditions If statements can be used If then ….. End if; Remember to end the if statement Use of indented code will make the code easier to debug!