H.Melikian1 PLSQL Dr.Hayk Melikyan Departmen of Mathematics and CS

Slides:



Advertisements
Similar presentations
Owners Roles DB Objects Grant Revoke Grant Revoke Grant Revoke (*) with admin option Il ruolo …. È un set di system & object privileges Non appartiene.
Advertisements

8 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Using Explicit Cursors.
PL/SQL.
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
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.
PL/SQL.
Murali Mani Persistent Stored Modules (Stored Procedures) : PSM.
PL/SQL (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
Chapter 4B: More Advanced PL/SQL Programming
Using Oracle PL/SQL PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural.
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.
PL/SQL The Oracle Programming Language. Purpose SQL is a non-procedural language. Often we need to put structure on transactions, so we use the supplemental.
Introduction to PL/SQL
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
Objectives Why PL-SQL ? Language features
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.
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.
SQL Training Procedures & Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. DB Procedures & Functions Procedures and Functions.
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.
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 Theory, Practice & Methodology of Relational Database Design and Programming Copyright © Ellis Cohen Cursors These slides are licensed under.
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
LECTURE 1 INTRODUCTION TO PL/SQL Tasneem Ghnaimat.
Advanced SQL Instructor: Mohamed Eltabakh 1 Part II.
CS178 Database Management PL/SQL session 8 References: ORACLE 9i PROGRAMMING A Primer Rajshekhar Sunderraman.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
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.
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.
Trigger Oracle PL/SQL. Triggers Associated with a particular table Associated with a particular table Automatically executed when a particular event occurs.
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)
SQL Fundamentals  SQL: Structured Query Language is a simple and powerful language used to create, access, and manipulate data and structure in the database.
Database Technology Jing Shen.
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
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.
ITEC 224 Database Programming PL/SQL Lab Cursors.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Chapter 5 : Integrity And Security  Domain Constraints  Referential Integrity  Security  Triggers  Authorization  Authorization in SQL  Views 
implicit and an explicit cursor
Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha Function, Trigger used in PosgreSQL.
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.
Database An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL Definition: PL/SQL.
1 Introduction to Database Systems, CS420 SQL Persistent Stored Modules (PSM) – Stored Procedure.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
CS422 Principles of Database Systems Stored Procedures and Triggers Chengyu Sun California State University, Los Angeles.
Pl/SQL LANGUAGE MULITPLE CHOICE QUESTION SET-3
PL/SQL.
PL/SQL MULTIPLE CHOICE QUESTION.
Cursors ITEC 224 Database Programming PL/SQL Lab.
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
PL/SQL week10.
Oracle9i Developer: PL/SQL Programming Chapter 8 Database Triggers.
Chapter 8 Advanced SQL.
PL/SQL Declaring Variables.
Chapter 8 Advanced SQL Pearson Education © 2009.
Modification to Views Via Triggers
Presentation transcript:

H.Melikian1 PLSQL Dr.Hayk Melikyan Departmen of Mathematics and CS

H.Melikian2 Program Structure PL/SQL like other programming languages, groups its statements into units called BLOCKS. Blocks can be unnamed (anonymous ) or named ( sub-programs). The subprograms can be either functions or procedures and they can be grouped into a packages. PL/SQL also allows access to databases via the cursors, triggers, stored procedures and functions.

H.Melikian3 Basic Structure of DECLARE -- Declarative section: -- variables, types, and local subprograms. BEGIN -- Executable section: -- procedural and SQL statements go here /* the only section of the block that is required. */ EXCEPTION -- Exception handling section: -- error handling statements go here END

H.Melikian4 What You Can and can’t ? The only SQL statements allowed in a PL/SQL program are SELECT, INSERT, UPDATE, DELETE and several other The SELECT statement has a special format. CREATE, DROP, or ALTER are not allowed. PL/SQL is not case sensitive C style comments (/*... */) or ( -- ….). To execute a PL/SQL program, we must follow the program text itself by a line with a single dot ("."), and then a line with run;

H.Melikian5 PL /SQL: Datatypes and Variables DESCRIPTION ( scalar data types) Numeric BINARY INTEGER Integer in the range to NATURAL Integer in the range 0 to 2 31 POSITIVE Integer in the range 1 to 2 31 NUMBER(p,s) Same as Oracle SQL's NUMBER, where p is the precision and s is the scale Character CHAR(N) Fixed-length character string of length N. VARCHAR2(N) Variable-length character string of maximum length N Boolean BOOLEAN Boolean data typ (TRUE, FALSE) Date-Time DATE Same as Oracle SQL's DATE

H.Melikian6 Variables and Types That type can be One of the types used by SQL for database columns A generic type used in PL/SQL such as NUMBER Declared to be the same as the type of some database column DECLARE price NUMBER; myBeer VARCHAR(20); or DECLARE myBeer Beers.name%TYPE;

H.Melikian7 Variables and Types(2) A variable may also have a type that is a record with several fields. The simplest way to declare such a variable is to use %ROWTYPE on a relation name DECLARE beerTuple Beers%ROWTYPE; The initial value of any variable, regardless of its type, is NULL. *

H.Melikian8 PL/SQL: Anchored Declarations cnum customers.cno%type; cname customers.cname%type; commission REAL(5,2) := 12.5; x commission%type; Anchored variables are synchronized with the database columns. The database columns may change their datatypes and the PL/SQL program remains compatible. Anchored variables declared within the PL/SQL program are normalized, i.e. changing one data type does not a_ect how the corresponding anchored variables will be used. Anchored data types are evaluated at compile time.

H.Melikian9 Variables and Types(3) We can assign values to variables, using the ":=" operator. The assignment can occur either immediately after the type of the variable is declared, or anywhere in the executable portion of the program. An exampl DECLARE a NUMBER := 3; BEGIN a := a + 1; END;. run;

H.Melikian10 PL/SQL: Variable/Constant Declarations i BINARY_INTEGER; cno NUMBER(5) NOT NULL := 1111; cname VARCHAR2(30); commision NUMBER(5,2) := 12.5; MAXCOLUMNS CONSTANT INTEGER(2) := 30; hired_date DATE; done BOOLEAN; Any variable that is declared to be NOT NULL must be initialized in its declaration. All variables that are not defined to be NOT NULL are initialized to have the value NULL.

H.Melikian11 Simple Programs in PL/SQL After the SELECT clause, we must have an INTO clause listing variables, one for each attribute in the SELECT clause, into which the components of the retrieved tuple must be placed. CREATE TABLE T1( e INTEGER, f INTEGER ); DELETE FROM T1; INSERT INTO T1 VALUES(1, 3); INSERT INTO T1 VALUES(2, 4); Above is plain SQL; below.

H.Melikian12 NEXT DECLARE a NUMBER; b NUMBER; BEGIN SELECT e,f INTO a,b FROM T1 WHERE e>1; INSERT INTO T1 VALUES(b,a); END;. run; /*this is the PL/SQL program

H.Melikian13 Control Flow in PL/SQL There are three version of of statement in PL/SL: if-then: IF THEN END IF; if-then-else: IF THEN ELSE END IF; if (cnum > 10) and (cnum < 90) then i := i + 1; dbms_output.put_line('Cust ' || cnum); end if; if (cnum > 10) and (cnum < 90) then i := i + 1; dbms_output.put_line('Valid Cust ' || cnum); else j := j + 1; dbms_output.put_line('Invalid Cust ' || cnum); end if;

H.Melikian14 if –then- elsif statement IF THEN statement-list-1 ELSIF THEN statement-list-2 ELSIF THEN statement-list-n ELSE statement-list-n+1 END IF; if (score > 90) then na := na + 1; elsif (score > 80) then nb := nb + 1; elsif (score > 70) then nc := nc + 1; elsif (score > 60) then nd := nd + 1; else nf := nf + 1; end if;

H.Melikian15 Exampole DECLARE a NUMBER; b NUMBER; BEGIN SELECT e,f INTO a,b FROM T1 WHERE e > 1; IF b=1 THEN INSERT INTO T1 VALUES(b,a); ELSE INSERT INTO T1 VALUES(b+10,a+10); END IF; END;. run;

H.Melikian16 Loops Loops are created with the following: LOOP /*A list of statements. */ END LOOP; At least one of the statements in should be an EXIT statement of the form EXIT WHEN ; The loop breaks if is true. For example, here is a way to insert each of the pairs (1, 1) through (100, 100) into T1 of the above two examples:

H.Melikian17 Example DECLARE i NUMBER := 1; BEGIN LOOP INSERT INTO T1 VALUES(i, i); i := i+1; EXIT WHEN i>13; END LOOP; END;. run; loop i := i + 1; if i > 10 then exit; end if; sum := sum + i; end loop;

H.Melikian18 Other loop-forming statements EXIT by itself is an unconditional loop break. Use it inside a conditional if you like. A WHILE loop can be formed with WHILE LOOP END LOOP; A simple FOR loop can be formed with: FOR IN.. LOOP END LOOP; Here, can be any variable; it is local to the for Loop and need not be declared. Also, and are constants.

H.Melikian19 Cursors A cursor is a variable that runs through the tuples of some relation. This relation can be a stored table, or it can be the answer to some query. By fetching into the cursor each tuple of the relation, we can write a program to read and process the value of each such tuple. If the relation is stored, we can also update or delete the tuple at the current cursor position. Cursor [ return ] is ; Once a cursor has been declared, it can beproccessed using open, fetch and close statements; Open ; Fetch into ; Close ;

H.Melikian20 The nest example illustrates a cursor loop. It uses our example relation T1 (e,f) whose tuples are pairs of integers. The program will delete every tuple whose first component is less than the second, and insert the reverse tuple into T1. DECLARE a T1.e%TYPE; b T1.f%TYPE; CURSOR T1 cursor IS SELECT e, f FROM T1 WHERE e < f FOR UPDATE;

H.Melikian21 BEGIN OPEN T1Cursor; LOOP FETCH T1Cursor INTO a, b; EXIT WHEN T1Cursor%NOTFOUND; DELETE FROM T1 WHERE CURRENT OF T1Cursor; INSERT INTO T1 VALUES(b, a); END LOOP; CLOSE T1Cursor; END;. run

H.Melikian22 PL/SQL: Cursors CURSOR c1 RETURN customers%ROWTYPE IS select * from customers; CURSOR c2 IS select pno, pname, price*markdown sale_price from parts; _ Cursor c1 uses the RETURN clause which is consistent with the select list of the select statement in the SQL query associated with the cursor. _ Cursor c2 uses a PL/SQL variable markdown in the select statement associated with the cursor. Cursor attributes are %found, %notfound, %rowcount, %isopen Example:

H.Melikian23 DECLARE CURSOR c1 IS select cno,cname,city from customers,zipcodes where customers.zip = zipcodes.zip; c1_rec c1%rowtype; BEGIN if not c1%isopen then open c1; end if; fetch c1 into c1_rec; while c1%found loop dbms_output.put_line('Row Number ' || c1%rowcount || '> ' || c1_rec.cno || ' ' || c1_rec.cname || ' ' || c1_rec.city); fetch c1 into c1_rec; end loop; close c1; END;

H.Melikian24 Cursor for loop DECLARE CURSOR c1 IS select cno,cname,city from customers,zipcodes where customers.zip = zipcodes.zip; BEGIN for c1_rec in c1 loop dbms_output.put_line('Row Number ' || c1%rowcount || '> ' || c1_rec.cno || ' ' || c1_rec.cname || ' ' || c1_rec.city); end loop; END; here we have implicit cursors for i in (select * from employees) loop... end loop;

H.Melikian25 Functions DECLARE enum customers.cno%type; total number(10,2); status boolean; function total_emp_sales(emp_no IN employees.eno%type) return number is sales number; begin select sum(price*qty) into sales from orders, odetails, parts where orders.eno = emp_no and orders.ono = odetails.ono and odetails.pno = parts.pno; return (sales); end;

H.Melikian26 Example1 BEGIN enum := 1000; total := total_emp_sales(enum); DBMS_OUTPUT.PUT_LINE('Total sales for employee ' || enum || ' is ' || total); END;

H.Melikian27 Stored Procedure and Functions CREATE [ or replace] procedure [ ( )] as BEGIN [ exception ] END;

H.Melikian28 Function (Example_1) create [ or replace] function ( ) return as begin [exception ] end;

H.Melikian29 Function Example_2 Create or replace function get_city(cname in customers.cno%type) return zipcodes.city%type as ccity zipcodes.city%type; Begin select city into ccity from customers, zipcodes where cno = cnum and customers.zip = zipcodes.sip; return (ccity); End;

H.Melikian30 Triggers An SQL trigger is a mechanism that automatically executes a specified PL/SQL block ( triggers action) when a triggering event occurs on table. The triggering event may be one of insert, delete or update. The trigger is associated with DB table and is fired when the triggering event takes place on the table. Triggers are created in Oracle using the Create trigger statement whose syntax is

H.Melikian31 Create Trigger(syntax) create [or replace] trigger {before | after} { delete | insert | update[ of column [, column] …]} [ or { delete | insert | update[ of column [, column] …]}] … ON [ [referencing { old [as] [new [as] ] | new [as] [ old [as] ]}] For each row [when (codition)]] PL/SQL_ blo ck

H.Melikian32 Example create or replace trigger update_price_of_parts after update of price on parts for each row begin insert into parts_log values(:old.pno, user, sysdate, ; old.price, :new.price); end;