Darshan Institute of Engineering & Technology PL_SQL



Similar documents
Introduction to PL/SQL Programming

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

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

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

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

Chapter 8: Introduction to PL/SQL 1

Persistent Stored Modules (Stored Procedures) : PSM

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

Oracle Database: SQL and PL/SQL Fundamentals

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

Oracle Database: SQL and PL/SQL Fundamentals NEW

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

Oracle Database: SQL and PL/SQL Fundamentals

An Introduction to PL/SQL. Mehdi Azarmi

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

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

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

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

Database Programming with PL/SQL: Learning Objectives

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

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

Intro to Embedded SQL Programming for ILE RPG Developers

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

14 Triggers / Embedded SQL

Training Guide. PL/SQL for Beginners. Workbook

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

Oracle For Beginners Page : 1

Oracle Database: Develop PL/SQL Program Units

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

Oracle SQL. Course Summary. Duration. Objectives

Oracle 10g PL/SQL Training

Oracle 11g PL/SQL training

Oracle Database: Program with PL/SQL

Oracle Database 12c: Introduction to SQL Ed 1.1

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

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

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

Maintaining Stored Procedures in Database Application

Oracle Database: Program with PL/SQL

SQL Server. 1. What is RDBMS?

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database 10g: Program with PL/SQL

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

SQL Server Database Coding Standards and Guidelines

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

CS 632 Advanced Database Systems Object-Relational Database (ORDB) Dr. H. Assadipour

Oracle Database: Program with PL/SQL

SQL - QUICK GUIDE. Allows users to access data in relational database management systems.

Oracle Database: Program with PL/SQL

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

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

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

Oracle Database: Program with PL/SQL

Using SQL in RPG Programs: An Introduction

Introduction to Database. Systems HANS- PETTER HALVORSEN,

Oracle Database: Introduction to SQL

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

CHAPTER 2 DATABASE MANAGEMENT SYSTEM AND SECURITY

SQL. Short introduction

Oracle Database: Introduction to SQL

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

PL/SQL. Database Procedural Programming PL/SQL and Embedded SQL. Procedures and Functions

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

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

Oracle Database 10g Express

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

How To Create A Table In Sql (Ahem)

Querying Microsoft SQL Server

Embedded SQL programming

Oracle Database 11g SQL

Oracle Database: Introduction to SQL

New SQL Features in Firebird 3

Programming Database lectures for mathema

SQL Server An Overview

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Chapter 5 More SQL: Complex Queries, Triggers, Views, and Schema Modification

PL/SQL: Introduction. Overview. Anonymous Blocks and Basic Language Features

DECLARATION SECTION. BODY STATEMENTS... Required

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

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

ATTACHMENT 6 SQL Server 2012 Programming Standards

Oracle Database 11g: Program with PL/SQL

Course ID#: W 35 Hrs. Course Content

Handling PL/SQL Errors

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

BCA. Database Management System

2874CD1EssentialSQL.qxd 6/25/01 3:06 PM Page 1 Essential SQL Copyright 2001 SYBEX, Inc., Alameda, CA

Querying Microsoft SQL Server 20461C; 5 days

Oracle(PL/SQL) Training

SAP HANA SQLScript Reference

MS SQL Performance (Tuning) Best Practices:

CSC 443 Database Management Systems. The SQL Programming Language

Data security best practices

MOC 20461C: Querying Microsoft SQL Server. Course Overview

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

1 File Processing Systems

Querying Microsoft SQL Server Course M Day(s) 30:00 Hours


Transcription:

Explain the advantages of PL/SQL. Advantages of PL/SQL Block structure: PL/SQL consist of block of code, which can be nested within each other. Each block forms a unit of a task or a logical module. PL/SQL blocks can be stored in the database and reused. Procedural language capability: PL/SQL consist of procedural constructs such as conditional statements (if, if else, nested if, else if ladder) and loops (for, while, do while). Better performance: PL/SQL engine processes multiple SQL statements simultaneously as a single block, thereby reducing network traffic. Error handling: PL/SQL handles errors or exceptions effectively during the execution of PL/SQL program. Once an exception is caught, specific action can be taken depending upon the type of the exception or it can be displayed to the user with message. Write short note on stored procedure in PL/SQL. Explain stored procedures in PL/SQL. A stored procedure (proc) is a group of PL/SQL statements that performs specific task. A procedure has two parts, header and body. The header consists of the name of the procedure and the parameters passed to the procedure. The body consists of declaration section, execution section and exception section. A procedure may or may not return any value. A procedure may return more than one value. General Syntax to create a procedure CREATE [ REPLACE] PROCEDURE proc_name [list of parameters] IS Declaration section Execution section EXCEPTION Exception section Explanation Create:-It will create a procedure. Replace:- It will re-create a procedure if it already exists. We can pass parameters to the procedures in three ways. 1. IN-parameters: - These types of parameters are used to send values to stored procedures. 2. OUT-parameters: - These types of parameters are used to get values from stored procedures. This is similar to a return type in functions but procedure can return values for more than one parameters. 3. IN OUT-parameters: - This type of parameter allows us to pass values into a procedure and get output values from the procedure. IS indicates the beginning of the body of the procedure. The code between IS and forms the Declaration section. Begin:-It contains the executable statement. Exception:- It contains exception handling part. This section is optional. End:- It will end the procedure. 1 Prof. Firoz Sherasiya (9879879861) 2130703 Database Management System

The syntax within the brackets [ ] indicates that they are optional. By using CREATE REPLACE together the procedure is created if it does not exist and if it exists then it is replaced with the current code. How to execute a Stored Procedure? There are two ways to execute a procedure. 1) From the SQL prompt. Syntax: EXECUTE [or EXEC] procedure_name (parameter); 2) Within another procedure simply use the procedure name. Syntax: procedure_name (parameter); Example 1 (Using IN) CREATE REPLACE PROCEDURE get_studentname_by_id (id IN NUMBER) IS SELECT studentname FROM stu_tbl WHERE studentid = id; Execute:- EXECUTE get_studentname_by_id(10); get_studentname_by_id(10); Explanation:- Above procedure gives the name of student whose id is 10. Example 2 (Using OUT) CREATE REPLACE PROCEDURE multiplication @mult1 int, @mult2 int, @result int OUTPUT as select @result = @mult1 * @mult2 Execute:- EXECUTE multiplication (5,6); multiplication (5,6); Explanation:- Above procedure gives the multiplication of 4 and 6 that is equal to 30. Advantages of procedure Security:- We can improve security by giving rights to selected persons only. Faster Execution:- It is precompiled so compilation of procedure is not required every time you call it. Sharing of code:- Once procedure is created and stored, it can be used by more than one user. Productivity:- Code written in procedure is shared by all programmers. This eliminates redundant coding by multiple programmers so overall improvement in productivity. Explain database trigger with example. Write short note on database triggers in PL/SQL. What is trigger? Explain its type with their syntax. A trigger is a PL/SQL block structure which is triggered (executed) automatically when DML statements like Insert, Delete, and Update is executed on a table. There are two types of triggers based on the level it is triggered. 2 Prof. Firoz Sherasiya (9879879861) 2130703 Database Management System

1. Row level trigger - An event is triggered when any row of the table is changed irrespective of insert, update or delete statement. 2. Statement level trigger - An event is triggered when particular SQL statement is executed, e.g. trigger on insert command. We cannot pass parameters into triggers like stored procedure. We cannot do transaction control (commit rollback) in trigger. Triggers are normally slow. When triggers can be used, 1. Based on change in one table, we want to update other table. 2. Automatically update derived columns whose values change based on other columns. 3. Logging. 4. Enforce business rules. Syntax of Trigger CREATE [ REPLACE] TRIGGER trigger_name [BEFE / AFTER] [INSERT / UPDATE / DELETE [of columnname]] ON table_name [REFERENCING [OLD AS old, NEW AS new]] [F EACH ROW [WHEN condition]] DECLARE Declaration section Executable statements CREATE [ REPLACE ] TRIGGER trigger_name:- This clause creates a trigger with the given name or overwrites an existing trigger. [BEFE AFTER]:- This clause indicates at what time the trigger should be fired. Before updating the table or after updating a table. [INSERT / UPDATE / DELETE]:- This clause determines on which kind of statement the trigger should be fired. Either on insert or update or delete or combination of any or all. More than one statement can be used together separated by keyword. The trigger gets fired at all the specified triggering event. [OF columnname]:- This clause is used when you want to trigger an event only when a specific column is updated. This clause is mostly used with update triggers. [ON table_name]:- This clause identifies the name of the table or view to which the trigger is related. [REFERENCING OLD AS old NEW AS new]:- This clause is used to reference the old and new values of the data being changed. By default, you reference the values as old.column_name or new.column_name. The reference names can also be changed from old or new to any other userdefined name. You cannot reference old values when inserting a record, or new values when deleting a record, because they do not exist. [F EACH ROW]:- This clause is used to determine whether a trigger must fire when each row gets affected ( i.e. a Row Level Trigger) or just once when the entire SQL statement is executed(i.e.statement level Trigger). WHEN (condition):- The trigger is fired only for rows that satisfy the condition specified. This clause is valid only for row level triggers. 3 Prof. Firoz Sherasiya (9879879861) 2130703 Database Management System

Example 1 We are creating trigger that display message if we insert negative value or update value to negative value in bal column of account table. CREATE REPLACE TRIGGER balnegative BEFE insert update On account F EACH ROW IF :NEW.bal<0 THEN dbms.output.put.line ( balance is negative ) END IF; OUTPUT:- Trigger is created. Now when you perform insert operation on account table. SQL:> Insert into account (bal) values (-2000); Update account set bal=-5000 where bal=1000; It display following message before executing insert or update statement. Output:- Balance is negative. We get message that balance is negative it indicate that trigger has executed before the insertion or update operation. Example 2 CREATE TRIGGER trig1 AFTER insert ON T4 REFERENCING NEW AS newrow F EACH ROW WHEN (newrow.a <= 10) INSERT INTO T5 VALUES (newrow.a, newrow.b); OUTPUT:- Trigger is created. Explanation:- We have following two tables CREATE TABLE T4 (a INTEGER, b CHAR(10)); CREATE TABLE T5 (c INTEGER, d CHAR(10)); We have created a trigger that may insert a tuple into T5 when a tuple is inserted into T4. It will check that the record insert in T4 is 10 th or less than 10 th record if so then the same record is inserted into table T5. 4 Prof. Firoz Sherasiya (9879879861) 2130703 Database Management System

Example 3 CREATE TRIGGER Person_Check_Age AFTER insert update OF age ON Person F EACH ROW IF (:new.age < 0) THEN dbms.output.put.line('no negative age allowed'); END IF; OUTPUT:- Trigger is created. Explanation:-In above trigger if we are inserting negative value in Age column then it will give error. If we insert negative value in other column then it will not give any error. What is cursor? Explain with example. Write short note on cursors and its types. Cursors are database objects used to traverse the results of a select SQL query. It is a temporary work area created in the system memory when a select SQL statement is executed. This temporary work area is used to store the data retrieved from the database, and manipulate this data. It points to a certain location within a recordset and allow the operator to move forward (and sometimes backward, depending upon the cursor type). We can process only one record at a time. The set of rows the cursor holds is called the active set (active data set). Cursors are often criticized for their high overhead. There are two types of cursors in PL/SQL: 1. Implicit cursors: These are created by default by ACLE itself when DML statements like, insert, update, and delete statements are executed. They are also created when a SELECT statement that returns just one row is executed. We cannot use implicit cursors for user defined work. 2. Explicit cursors: Explicit cursors are user defined cursors written by the developer. They can be created when a SELECT statement that returns more than one row is executed. Even though the cursor stores multiple records, only one record can be processed at a time, which is called as current row. When you fetch a row, the current row position moves to next row. Attributes of Cursor:- Attributes Return Value Example %FOUND It will return TRUE, if the DML statements like INSERT, DELETE, UPDATE and SELECT will affect at least one row else return FALSE SQL%FOUND 5 Prof. Firoz Sherasiya (9879879861) 2130703 Database Management System

%NOTFOUND It will return FALSE, if the DML statements like INSERT, SQL%NOTFOUND DELETE, UPDATE and SELECT will affect at least one row else return TRUE %ROWCOUNT Return the number of rows affected by the DML operations SQL%ROWCOUNT INSERT, DELETE, UPDATE, SELECT %ISOPEN It will return true if cursor is open else return false. SAL%OPEN Steps to manage explicit cursor:- 1) Declare a cursor:- A cursor is defined in the declaration section of PL/SQL block. CURS cursorname IS SELECT 2) Open a cursor:- Once cursor is declared we can open it. When cursor is opened following operations are performed. a. Memory is allocated to store the data. b. Execute SELECT statement associated with cursor c. Create active data set by retrieving data from table d. Set the cursor row pointer to point to first record in active data set. OPEN cursorname; 3) Fetching data:- We cannot process selected row directly. We have to fetch column values of a row into memory variables. This is done by FETCH statement. FETCH cursorname INTO variable1, variable2. 4) Processing data:- This step involves actual processing of current row. 5) Closing cursor:- A cursor should be closed after the processing of data completes. Once you close the cursor it will release memory allocated for that cursor. CLOSE cursorname; Example:- DECLARE CURS emp_cur IS SELECT emp_rec FROM emp_tbl WHERE salary > 10000; OPEN emp_cur; FETCH emp_cur INTO emp_rec; dbms_output.put_line (emp_rec.first_name ' ' emp_rec.last_name); CLOSE emp_cur; 6 Prof. Firoz Sherasiya (9879879861) 2130703 Database Management System

Explanation:- In the above example, first we are delaring a cursor whose name is emp_cur with select query. In select query we have used where condition such that salary<10000. So active data set contain only such records whose salalry less than 10000. Then, we are opening the cursor in the execution section. Then we are fetching the records from cursor to the variable named emp_rec. Then we are displaying the first_name and last_name of records fetched in variable. At last as soon as our work completed e are closing the cursor. Write a PL/SQL block to print the sum of Numbers from 1 to 50. declare sum number:=0; begin for i in 1..50 loop sum:=sum+i; end loop; dbms_output.put_line('the sum of 100 natural nos is = ' sum); end; Write a PL/SQL block to print the given number is Odd or Even. declare A number(5) begin a:=&a; if(a mod 2=0) then dbms_output.put_line('number of odd'); else dbms_output.put_line('number of odd'); end if; end; 7 Prof. Firoz Sherasiya (9879879861) 2130703 Database Management System