CURSORS AND TRIGGERS

Similar documents
ORACLE 9I / 10G / 11G / PL/SQL COURSE CONTENT

PL/SQL (Cont d) Let s start with the mail_order database, shown here:

Darshan Institute of Engineering & Technology PL_SQL

Oracle 11g PL/SQL training

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Database Programming with PL/SQL: Learning Objectives

Training Guide. PL/SQL for Beginners. Workbook

DECLARATION SECTION. BODY STATEMENTS... Required

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals

Oracle Database: Program with PL/SQL

Oracle For Beginners Page : 1

Oracle Database: Program with PL/SQL

Oracle Database: Program with PL/SQL

Oracle Database: SQL and PL/SQL Fundamentals NEW

14 Triggers / Embedded SQL

Introduction to PL/SQL Programming

Oracle Database: Program with PL/SQL

1 Stored Procedures in PL/SQL 2 PL/SQL. 2.1 Variables. 2.2 PL/SQL Program Blocks

Procedural Extension to SQL using Triggers. SS Chung

Oracle Database 11g Express Edition PL/SQL and Database Administration Concepts -II

Handling Exceptions. Copyright 2006, Oracle. All rights reserved. Oracle Database 10g: PL/SQL Fundamentals 8-1

Oracle Database: Program with PL/SQL

Oracle PL/SQL Best Practices

Oracle For Beginners Page : 1

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

Handling PL/SQL Errors

Writing Control Structures

Database programming 20/08/2015. DBprog news. Outline. Motivation for DB programming. Using SQL queries in a program. Using SQL queries in a program

Duration Vendor Audience 5 Days Oracle End Users, Developers, Technical Consultants and Support Staff

Persistent Stored Modules (Stored Procedures) : PSM

Handling Exceptions. Schedule: Timing Topic. 45 minutes Lecture 20 minutes Practice 65 minutes Total

Handling Exceptions. Schedule: Timing Topic 45 minutes Lecture 20 minutes Practice 65 minutes Total

How To Name A Program In Apl/Sql

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database: Develop PL/SQL Program Units

VARRAY AND NESTED TABLE

Oracle PL/SQL Language. CIS 331: Introduction to Database Systems

5. CHANGING STRUCTURE AND DATA

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

PL/SQL Overview. Basic Structure and Syntax of PL/SQL

CSC 443 Database Management Systems. The SQL Programming Language

Duration Vendor Audience 5 Days Oracle Developers, Technical Consultants, Database Administrators and System Analysts

Oracle 10g PL/SQL Training

Review your answers, feedback, and question scores below. An asterisk (*) indicates a correct answer.

Oracle to MySQL Migration

9 Using Triggers. Using Triggers 9-1

Topics Advanced PL/SQL, Integration with PROIV SuperLayer and use within Glovia

COMS20700 DATABASES 13 PL/SQL. COMS20700 Databases Dr. Essam Ghadafi

Overview of PL/SQL. About PL/SQL

Elena Baralis, Silvia Chiusano Politecnico di Torino. Pag. 1. Active database systems. Triggers. Triggers. Active database systems.

Handling Exceptions. Copyright 2008, Oracle. All rights reserved.

Oracle Database 11g: Program with PL/SQL

PROCEDURES, FUNCTIONS AND PACKAGES

When an exception occur a message which explains its cause is received. PL/SQL Exception message consists of three parts.

Programming Database lectures for mathema

Oracle Database 10g: Program with PL/SQL

Error Management in Oracle PL/SQL

Why programming extensions? to program complex update transactions. where referential integrity is not addressed by data definition

1 Triggers. 2 PL/SQL Triggers

STUDY OF PL/SQL BLOCK AIM: To Study about PL/SQL block.

Handling PL/SQL Errors

Course -Oracle 10g SQL (Exam Code IZ0-047) Session number Module Topics 1 Retrieving Data Using the SQL SELECT Statement

Intro to Embedded SQL Programming for ILE RPG Developers

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

A basic create statement for a simple student table would look like the following.

Chapter 8: Introduction to PL/SQL 1

SQL Introduction Chapter 7, sections 1 & 4. Introduction to SQL. Introduction to SQL. Introduction to SQL

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Data Masking. Procedure

MONASH UNIVERSITY. Faculty of Information Technology

2. Which of the following declarations is invalid? Mark for Review (1) Points

Oracle SQL. Course Summary. Duration. Objectives

Introduction to Oracle PL/SQL Programming V2.1 - Lessons 11-End

What is the value of SQL%ISOPEN immediately after the SELECT statement is executed? Error. That attribute does not apply for implicit cursors.

Oracle9i: Develop PL/SQL Program Units

Oracle Database 12c: Introduction to SQL Ed 1.1

Oracle(PL/SQL) Training

RDBMS Using Oracle. Lecture Week 7 Introduction to Oracle 9i SQL Last Lecture. kamran.munir@gmail.com. Joining Tables

Oracle Database 10g: Introduction to SQL

An Oracle White Paper June RESTful Web Services for the Oracle Database Cloud - Multitenant Edition

Structured Query Language. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics

Making the Most of Oracle PL/SQL Error Management Features

Oracle For Beginners Page : 1

PL / SQL Basics. Chapter 3

Lab # 5. Retreiving Data from Multiple Tables. Eng. Alaa O Shama

Oracle For Beginners Page : 1

Oracle Database: Introduction to SQL

Data security best practices

Introduction to Triggers using SQL

SQL Server. 1. What is RDBMS?

Creating PL/SQL Blocks. Copyright 2007, Oracle. All rights reserved.

Performance Implications of Various Cursor Types in Microsoft SQL Server. By: Edward Whalen Performance Tuning Corporation

Oracle Database 10g: PL/SQL Fundamentals

Oracle PL/SQL Injection

Real SQL Programming. Persistent Stored Modules (PSM) PL/SQL Embedded SQL

PL/SQL Programming Concepts: Review. Copyright 2004, Oracle. All rights reserved.

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Oracle Database: Introduction to SQL

Transcription:

CURSORS AND TRIGGERS Q1. a) What is a cursor? What types of cursors are supported in PL/SQL? Explain Cursor attributes. b) What is the purpose of cursor in PL/SQL? Name the types of cursors used in PL/SQL? Explain Cursor attributes. c) What is the importance of cursor for loop? How it simplifies the operation? Explain with suitable example. Answers: (a) The oracle uses a work area of memory to execute SQL statements. This work area is also called context area and data stored in this context area is called the Active Data Set. A cursor is a pointer to this context area. Types of cursors: There are two types of cursors: (i) Implicit Cursor (ii) Explicit Cursor Implicit Cursor The oracle implicitly (internally or automatically) opens a cursor for each SQL statement. Since the implicit cursors are opened and managed by oracle internally. So there is no need to open and manage the cursors by the user. Implicit cursor attributes can be used to access information about status of last insert, update, delete or single row select statement. Explicit Cursor When individual records in a table have to be processed inside a PL/SQL code block a cursor is used. This cursor will be declared and mapped to an SQL query in the Declare Section of the PL/SQL block and used within the Executable Section. This cursor needs to be opened before the reading of the rows can be done, after which the cursor is closed. Cursor marks the current position in an active set. A cursor thus created and used is known as an Explicit Cursor. Cursor Attributes Cursors have the following four attributes: Attribute Name Description %ISOPEN It is true if cursor is open and FALSE if cursor is not open or cursor is closed. It is used only with Explicit Cursors. %FOUND TRUE if at least one row was processed or a record was fetched successfully from the opened cursor and FALSE otherwise. %NOTFOUND TRUE if no row were processed or if record was not fetched successfully and FALSE otherwise. %ROWCOUNT It returns the number of rows/records processed by a cursor. (b) The most commonly used loop with in a PL/SQL block is the FOR variable IN value construct. This is an example of machine defined loop exit i.e. when all the values in FOR construct are exhausted looping stops. Syntax: FOR variable IN cursorname Here, the verb FOR automatically creates the variable of type %rowtype. Each record in the opened cursor becomes a value for the memory variable of %rowtype. The FOR verb ensures that a row from the cursor is loaded in declared variable and loop executes once. This goes until all the rows of the cursor have been loaded into the variable. After this loop stops. A CURSOR FOR automatically does the following: Implicitly declares its loop index as a %rowtype record. Open a cursor. Fetches a row from the active set for each loop iteration. Closes the cursor when all rows have been processed. Cursor can be closed even when an exit or goto statement is used to leave the loop prematurely, or an exception is raised inside the loop. Example The HRD manager has decided to raise the salary for all employees in department number 30 by 0.05. Table Name: Empno Deptno Sal 100 10 5000

101 30 6000 102 20 4000 103 30 5500 CURSOR c_emp IS SELECT empno,sal FROM emp WHERE deptno=30; FOR rec IN c_emp UPDATE emp SET sal=rec.sal+(rec.sal *.05) WHERE empno=rec.empno; COMMIT; The above PL/SQL code block will function as follows: The block implicitly declares rec as belonging to type c_emp%rowtypw and retrieves all the records having deptno 20.the salary for each record will be updated as required one by one and loaded into rec by the FOR verb. The cursor closes automatically when all the records in the cursor have been processed. This situation is sensed by FOR verb which causes the loop to exit. (c) (i) Active Data Set (ii) SQL%ISOPEN (iii) Explicit (iv) END. Q2. Answers the questions based on the table EMP given below: Table: EMP Column Name Data Type Size Description Empno Ename Job Sal DeptNo Commission VARCHAR2 VARCHAR2 4 30 15 8,2 2 7,2 Employee s Identification Number Employee s Name Employee s Designation Employee s Salary Employee s Department id Employee s Commission (a) Write a PL/SQL code to display the Empno, Ename and Job of employees of DeptNo 10 with CURSOR FOR Statement. (b) Write a PL/SQL code to increase the salary of employees according to the following conditions: Salary of DeptNo 10 employees increased by 1000. Salary of DeptNo 20 employees increased by 500. Salary of DeptNo 30 employees increased by 800. Also store the EmpNo, old salary and new salary in a Table TEMP having three columns Empid, Old and New. (c) Create a trigger on EMP table which verify that no record has the Commission greater than salary of an employee in table Emp. (d) Suppose the table Result in the database, which has the following structure: Result (RollNo, Sub1, Sub2, Sub3, Sub4, Total, Percentage). The RollNo and marks in each subject is stored in database. Write a PL/ SQL code to calculate the Total and Percentage of each student and update the database. Ans. (a) CURSOR C1 IS SELECT EMPNO, ENAME, JOB FROM EMP WHERE DEPTNO = 10;

FOR REC IN C1 DBMS_OUTPUT.PUT_LINE ( EMPNO REC.EMPNO); DBMS_OUTPUT.PUT_LINE ( ENAME REC.ENAME); DBMS_OUTPUT.PUT_LINE ( JOB REC.JOB); (b) OLDSAL ; NEWSAL ; CURSOR C1 IS SELECT * FROM EMP; REC C1%ROWTYPE; OPEN C1; FETCH C1 INTO REC EXIT WHEN C1%NOTFOUND; SELECT SAL INTO OLDSAL FROM EMP WHERE EMPNO=REC.EMPNO; IF REC.DEPTNO=10 THEN UPDATE EMP SET SAL=SAL+1000 WHERE EMPNO=REC.EMPNO; IF REC.DEPTNO=20 THEN UPDATE EMP SET SAL=SAL+500 WHERE EMPNO=REC.EMPNO; IF REC.DEPTNO=30 THEN UPDATE EMP SET SAL=SAL+800 WHERE EMPNO=REC.EMPNO; INSERT INTO TEMP (EMPID, OLD, NEW) VALUES (REC.EMPNO, OLDSAL, NEWSAL); CLOSE; (c) CREATE OR REPLACE TRIGGER UPDATE_CHECK BEFORE UPDATE ON EMP FOR EACH ROW IF :NEW.SAL<:OLD.SAL THEN RAISE_APPLICATION_ERROR (-20001, NEW SALARY CANNOT BE LESS THAN OLD SALARY ); (d) T ; PER ; CURSOR C1 IS SELECT * FROM RESULT; REC C1%ROWTYPE; OPEN C1; FETCH C1 INTO REC;

EXIT WHEN C1%NOTFOUND; T := REC.S1+REC.S2+REC.S3+REC.S4; PER:=T/4; UPDATE RESULT SET TOTAL=T, PERCENTAGE=PER WHERE RNO=REC.RNO; CLOSE C1; Q 3. (a) What is trigger? Write the syntax for defining a trigger. (b) Differentiate between row-level and statement-level triggers. (c) What are the advantages/uses of using triggers? (d) What is the default type of triggers? (e) What is instead of trigger? Answer (a) A trigger is a stored procedure that is automatically fired (executed) when an INSERT, UPDATE or DELETE statements issued against the associated table. The trigger is not explicitly called by user. A trigger defines an action the database should take when some database related events occur. A trigger can include SQL and PL/SQL statements to execute it as a unit and it can invoke other stored procedures. Syntax: CREATE [or REPLACE] TRIGGER trigger_name BEFORE AFTER DELETE OR INSERT OR UPDATE [OF column_name, ] Triggering ON table_name [FOR EACH ROW [WHEN condition]] Triggering Restriction event variable declaration; constant declaration; PL/SQL subprogram body; [EXCEPTION exception PL/SQl block;] Triggering Action (b) Row Level Trigger-> a row level trigger is fired each time a row in the table affected by the triggering statement. For example, if an UPDATE statement updates multiple rows of a table, a row trigger is fired once for each row affected by the UPDATE statement. If the triggering statement affects no rows, the trigger is not executed at all. Row level triggers are created by using FOR EACH ROW clause in the CREATE TRIGGER command. Statement Level Trigger -> A statement trigger is fired once on behalf of the triggering statement, independent of the number of rows the triggering statement affects. A statement trigger fires even if no row affected. For example when an UPDATE command update 10 rows, the commands contained in the trigger executed only once and not for every processed row. Statement level triggers are the default types of triggers created by the CREATE TRIGGER command. (c) Advantages of Triggers: To enforce complex integrity constraints. To prevent invalid transactions. To maintain replicate tables. To audit data modifications. To enforce complex security authorizations. To enforce complex business rules.

Q 4. (d) Statement level triggers are the default types of triggers created by the CREATE TRIGGER command. (e) An INSTEAD OF trigger is defined on a view rather than on a table. Such triggers are used to overcome the restrictions placed by Oracle on any view, which is non-updateable. Prior to version 7.3, it was impossible to issue DML statements- INSERT, DELETE, UPDATE- against any view which contained a join. In oracle 8, INSTEAD OF triggers are defined on the same event as their table counterparts: INSERT, DELETE and UPDATE.INSTEAD OF triggers give us the ability to perform DML against any view definition. There are few restrictions on INSTEAD OF triggers: They are available only at row level. They can be applied only on views and not to tables. a) Create a trigger, which verify that updated salary of employee must be greater than his/her previous salary. b) Find the errors from the following PL/SQL code and rewrite the corrected code underlining the correction made: CREATE ASWELLAS REPLACE TRIGGER DEPT_UP AFTER UPDATE ON EMP FOR EVERY ROW v_num (3); SELECT COUNT (*) INTO v_num FROM EMP WHERE deptno=20; IF v_num > 5 Raise_application_error (-20001, Cannot Exceed 5 ); Answer (a) CREATE OR REPLACE TRIGGER EMP_SUNDAY BEFORE INSERT OR UPDATE OR DELETE ON EMP IF RTRIM (UPPER (TO_CHAR (SYSDATE, DAY ))) = SUNDAY THEN RAISE_APPLICATION_ERROR (-20002, NO OPERATION CAN BE PERFORMED ON SUNDAY ); (b) CREATE OR REPLACE TRIGGER UPDATE_CHECK BEFORE UPDATE ON EMP IF :NEW.SAL < :OLD.SAL THEN RAISE_APPLICATION_ERROR (-20003, NEW SALARY CAN NOT BE LESS THAN OLD SALARY ); (c) CREATE OR REPLACE TRIGGER DEPT_UP AFTER UPDATE ON EMP FOR EACH ROW v_num (3); SELECT COUNT (*) INTO v_num FROM EMP WHERE deptno=20; IF v_num > 5 THEN Raise_application_error (-20001, Cannot Exceed 5 );