ADVANTAGES. Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine.

Similar documents
Contents I Introduction 1 Introduction to PL/SQL iii

Question: Which statement would you use to invoke a stored procedure in isql*plus?

PL/SQL Block structure

Lecture 08. Spring 2018 Borough of Manhattan Community College

Introduction to Computer Science and Business

5. Single-row function

Oracle Database 12c: Program with PL/SQL Duration: 5 Days Method: Instructor-Led

Oracle Database: Introduction to SQL/PLSQL Accelerated

Procedural Language Structured Query Language (PL/SQL)

Oracle Database: Program with PL/SQL

Oracle Database: Program with PL/SQL Ed 2

Oracle Database 11g: SQL and PL/SQL Fundamentals

Oracle Database 12c R2: Program with PL/SQL Ed 2 Duration: 5 Days

Conditionally control code flow (loops, control structures). Create stored procedures and functions.

Oracle PLSQL Training Syllabus

ORACLE TRAINING. ORACLE Training Course syllabus ORACLE SQL ORACLE PLSQL. Oracle SQL Training Syllabus

Oracle Developer Track Course Contents. Mr. Sandeep M Shinde. Oracle Application Techno-Functional Consultant

Introduction to SQL/PLSQL Accelerated Ed 2

Oracle Database: SQL and PL/SQL Fundamentals NEW

Oracle Database 11g: Program with PL/SQL Release 2

UNIT II PL / SQL AND TRIGGERS

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

SQL Interview Questions

UNIT-IV (Relational Database Language, PL/SQL)

OVERVIEW OF THE TYPES OF PL/SQL BLOCKS:

Oracle - Oracle Database: Program with PL/SQL Ed 2

IZ0-144Oracle 11g PL/SQL Certification (OCA) training

RDBMS - PL SQL - Topic 5 - MSBTE QUESTIONS AND ANSWERS

SQL+PL/SQL. Introduction to SQL

PL/SQL is a combination of SQL along with the procedural features of programming languages.

1Z0-144 Q&As Oracle Database 11g: Program with PL/ SQL

ORACLE: PL/SQL Programming

When a database trigger routine does not have to take place before the triggering event, which timing should you assign to the trigger?

Table of Contents. PDF created with FinePrint pdffactory Pro trial version

Programming in Oracle with PL/SQL. Procedural Language Extension to SQL

Oracle Database: Program with PL/SQL

Oracle Database 11g: Program with PL/SQL

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

INDEX. 1 Introduction. 2 Types of Cursors 2.1 Explicit cursor 2.2 Attributes 2.3 Implicit cursor 2.4 Attributes. 3 Parameterized cursor

Oracle PLSQL. Course Summary. Duration. Objectives

Introduction p. 1 The Logical and Physical View of Tables p. 1 Database Types p. 4 NULLs p. 6 DDL and DML Statements p. 7 Column and Table Constraint

2. Programming written ( main theme is to test our data structure knowledge, proficiency

Vendor: Oracle. Exam Code: 1Z Exam Name: Oracle Database 11g: Program with PL/ SQL. Version: Demo

ORACLE Job Placement Paper. Paper Type : General - other

Pace University. Fundamental Concepts of CS121 1

1Z Oracle Database 11g - Program with PL/SQL Exam Summary Syllabus Questions

Now, we can refer to a sequence without having to use any SELECT command as follows:

Persistent Stored Modules (Stored Procedures) : PSM

ORACLE TRAINING CURRICULUM. Relational Databases and Relational Database Management Systems

Oral Questions and Answers (DBMS LAB) Questions & Answers- DBMS

The PL/SQL Engine: PL/SQL. A PL/SQL Block: Declaration Section. Execution Section. Declaration Section 3/24/2014

Question Bank PL/SQL Fundamentals-I

STRUCTURED QUERY LANGUAGE (SQL)

CSC Web Programming. Introduction to JavaScript

PL / SQL Basics. Chapter 3

Slides by: Ms. Shree Jaswal

Database Programming with PL/SQL

Overview of PL/SQL. About PL/SQL. PL/SQL Environment. Benefits of PL/SQL. Integration

SEF DATABASE FOUNDATION ON ORACLE COURSE CURRICULUM

Table of Contents. Oracle SQL PL/SQL Training Courses

Database Programming with PL/SQL

Oracle Database 11g: PL/SQL Fundamentals

Oracle12c Release 1 PL/SQL (3 Days)

Oracle Exam 1z0-144 Oracle Database 11g: Program with PL/SQL Version: 8.5 [ Total Questions: 103 ]

The PCAT Programming Language Reference Manual

Exam Name: Oracle Database 11g: Program with PL/SQL

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

The SPL Programming Language Reference Manual

Oracle Database: Introduction to SQL Ed 2

1 Lexical Considerations

2 PL/SQL - fundamentals Variables and Constants Operators SQL in PL/SQL Control structures... 7

ORACLE DATABASE 12C INTRODUCTION

Lesson B Objectives IF/THEN. Chapter 4B: More Advanced PL/SQL Programming

Oracle PL/SQL - 12c & 11g [Basic PL/SQL & Advanced PL/SQL]

Oracle Database 10g: PL/SQL Fundamentals

Oracle Database: SQL and PL/SQL Fundamentals NEW

Actual4Test. Actual4test - actual test exam dumps-pass for IT exams

Oracle Database 10g: PL/SQL Fundamentals

Oracle Database 11g & PL/SQL

Introduction to Programming Using Java (98-388)

Oracle PL/SQL. DUMmIES. by Michael Rosenblum and Dr. Paul Dorsey FOR

Oracle Database: SQL and PL/SQL Fundamentals

Question No : 1 Which statement is true about triggers on data definition language (DDL) statements?

Oracle PL SQL Training & Certification

Database Programming with PL/SQL

ORACLE VIEWS ORACLE VIEWS. Techgoeasy.com

Databases 1. SQL/PSM and Oracle PL/SQL

XQ: An XML Query Language Language Reference Manual

Introduction to Explicit Cursors. Copyright 2008, Oracle. All rights reserved.

Database Systems: Design, Implementation, and Management Tenth Edition. Chapter 8 Advanced SQL

Lexical Considerations

SQL User Defined Code. Kathleen Durant CS 3200

Interview Questions on DBMS and SQL [Compiled by M V Kamal, Associate Professor, CSE Dept]

Oracle. Exam Questions 1Z Oracle 11g: Advanced PL/SQL. Version:Demo. 1Z0-146 Exam Questions Demo

Proje D2K. CMM (Capability Maturity Model) level Project Standard:- Corporate Trainer s Profile

SQL: Data De ni on. B0B36DBS, BD6B36DBS: Database Systems. h p:// Lecture 3

Oracle Database: Program with PL/SQL Ed 2 Erlernen Sie diese leistungsstarken Programmiersprache

Lexical Considerations

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

DATABASE DESIGN - 1DL400

Transcription:

1 PL/SQL

INTRODUCTION SQL does not have procedural capabilities. SQL does not provide the programming techniques of condition checking, looping and branching that is required for data before permanent storage. SQL statements are passed to the oracle engine one at time, each time an SQL statement will be executed, so each time need to call oracle engine. This will increase traffic on the network, so it reduce speed of data processing specially in client- server application. 2

INTRODUCTION If any error occur in SQL statement, the oracle engine will display its own error message, SQL has no facility to provide user friendly error. PL/SQL is superset of SQL. Procedural language extension SQL 3

ADVANTAGES OF PL/SQL PL/SQL provide facilities of conditional checking, branching and looping. PL/SQL dealing with error and facilities displaying user-friendly messages, when error occurred. PL/SQL allows declaration of variable, variable, we can use in intermediate result of query processing, or calculate values and insert them into table. PL/SQL can be used any where, either in SQL statements or PL/SQL blocks. 4

ADVANTAGES Via PL/SQL, all sorts of calculations can be done quickly and efficiently without use of Oracle engine. 5

PL/SQL BLOCKS PL/SQL code is built of Blocks, with a unique structure. There are two types of blocks in PL/SQL: 1. Anonymous Blocks: have no name (like scripts) can be written and executed immediately in SQLPLUS can be used in a trigger 2. Named Blocks: Procedures Functions 6

ANONYMOUS BLOCK STRUCTURE: DECLARE (optional) /* Here you declare the variables you will use in this block */ BEGIN (mandatory) /* Here you define the executable statements (what the block DOES!)*/ EXCEPTION (optional) /* Here you define the actions that take place if an exception is thrown during the run of this block */ END; / Always put a new line with only a / at the end of a block! (This tells Oracle to run the block) (mandatory) A correct completion of a block will generate the following message: 7 PL/SQL procedure successfully completed

DECLARE SECTION Code blocks start with a declaration section. Declaration of memory variables, constants, cursor etc. Once declared, they can be used in SQL statements for data manipulation. 8

BEGIN SECTION It consists of SQL executable statements as well as PL/SQL statements. Which describe processes that have to be applied to table data. Data manipulation, retrieval, looping and branching constructs are specified in this section. 9

THE EXCEPTION SECTION This section deals with handling of errors that occur during execution of the data manipulation statements. Errors can occur due to syntax, logic and/or validation rule. 10

THE CHARACTER SET The basic character set includes the following: Upper case Alphabets { A Z } Lower case alphabets { a- z } Number { 0 9 } Symbols ( ), * & @ etc. Words used in PL/SQL block are called Lexical Units. We can insert free blank spaces in lexical unit there will be no effect on PL/SQL block. 11

LITERALS Numeric literal It can be either integer of floats. If float is being represented, then the integer part must be separated from the float part by a period. Example 25, 6.34 etc 12

STRING LITERAL These are represented by one or more legal characters and must be enclosed with in single quotes. Example hello there 13

CHARACTER LITERAL These are string literal consisting of single characters. Example: *, A. 14

PL/SQL DATA TYPES The default data type can be use in PL/SQL. NUMBER CHAR DATE VARCHAR BOOLEAN 15

VARIABLES Variables in PL/SQL block are named variables. Variable must begin with character and can be followed by a maximum 29 other characters. Reserve words can not be used. Variables separated from each other by punctuation mark. White space can not be used in variable name. 16

ASSIGNING VALUES TO VARIABLE The assigning of a value to a variable can be done in two ways: Using the assignment operator := (i.e. a colon followed by an equal to sign and no space between :=). Selecting or fetching table data values into variables. 17

What is constant? CONSTANT Declaring a constant is similar to declaring a variable except that the keyword CONSTANT must be added to the variable name and a value assigned immediately. 18

DISPLAYING USER MESSAGE To display message, the SERVEROUTPUT should be set ON. SYNTAX: - SET SERVEROUTPUT [ON/OFF]; o DBMS_OUTPUT is a package that includes a number of procedure and function that we can use. o PUT_LINE puts a piece information in the package buffer followed by an end-of-line marker. 19

SIMPLE EXAMPLE 20

CONTROL STRUCTURE Conditional control Iterative control Sequential control. 21

Condition: If <cond> CONDITIONAL CONTROL then <command> elsif <cond2> then <command2> else <command3> end if; Nested conditions: If <cond> then if <cond2> then <command1> end if; else <command2> end if; 22

EXAMPLE OF IF STATEMENT 23

ITERATIVE CONTROL SIMPLE LOOP SYNTAX: LOOP <sequences of statements> END LOOP 24

EXAMPLE OF SIMPLE LOOP 25

WHILE LOOP Syntax WHILE <CONDITION> LOOP <ACTION> END LOOP; 26

EXAMPLE OF WHILE LOOP 27

FOR LOOP SYNTAX: FOR variable IN [REVERSE] start.end LOOP <ACTION> END LOOP; 28

EXAMPLE OF FOR LOOP 29

SIMPLE EXAMPLE 30

SIMPLE EXAMPLE-2 31

32

CURSOR The oracle engine uses a work area for its internal processing area in order to execute an SQL statement. This work area is private SQL S operation and is called a cursor. The data that is stored in the cursor is called the ACTIVE DATA SET. 33

TYPES OF CURSOR Implicit cursor: - if oracle engine opened a cursor for its internal processing, it is known as implicit cursor. Explicit cursor: - A cursor can also be opened for processing data through PL/SQL block. Such a user defined cursor is known as an Explicit cursor. 34

GENERAL CURSOR ATTRIBUTES Obtain status information about a cursor. Attribute Type Description %ISOPEN Boolean Evaluates to TRUE if the cursor is open. %NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row. %FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row; complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so far. 35

EXAMPLE OF CURSOR 36

37

ANOTHER EXAMPLE 38

EXPLICIT CURSOR The only means of generating an explicit cursor is for the cursor to be named in the DECLARE section of the PL/SQL Block. The advantages of declaring an explicit cursor over the indirect implicit cursor are that the explicit cursor gives more programmatic control to the programmer. Implicit cursors are less efficient than explicit cursors and thus it is harder to trap data errors. 39

EXPLICIT CURSOR The process of working with an explicit cursor consists of the following steps: DECLARING the cursor. This initializes the cursor into memory. OPENING the cursor. The previously declared cursor can now be opened; memory is allotted. FETCHING the cursor. The previously declared and opened cursor can now retrieve data; this is the process of fetching the cursor. CLOSING the cursor. The previously declared, opened, and fetched cursor must now be closed to release memory allocation. 40

DECLARING A CURSOR Declaring a cursor defines the name of the cursor and associates it with a SELECT statement. The first step is to Declare the Cursor with the following syntax: CURSOR c_cursor_name IS select statement Cursor names follow the same rules of scope and visibility that apply to the PL/SQL identifiers. Because the name of the cursor is a PL/SQL identifier, it must be declared before it is referenced. Any valid select statement can be used to define a cursor, including joins and statements with the UNION or MINUS clause. 41

OPENING CURSOR The next step in controlling an explicit cursor is to open it. When the Open cursor statement is processed, the following four actions will take place automatically: 1. The variables (including bind variables) in the WHERE clause are examined. 2. Based on the values of the variables, the active set is determined and the PL/SQL engine executes the query for that cursor. Variables are examined at cursor open time only. 3. The PL/SQL engine identifies the active set of data the rows from all involved tables that meet the WHERE clause criteria. 4. The active set pointer is set to the first row. 42

OPENING A CURSOR The syntax for opening a cursor is: OPEN cursor_name; 43

FETCHING ROWS IN A CURSOR After the cursor has been declared and opened, you can then retrieve data from the cursor. The process of getting the data from the cursor is referred to as fetching the cursor. There are two methods of fetching a cursor, done with the following command: FETCH cursor_name INTO PL/SQL variables; or FETCH cursor_name INTO PL/SQL record; 44

Syntax FETCHING ROWS IN A CURSOR FETCH cursorname into variable1, variable2. 45

EXPLICIT CURSOR EXAMPLE 46

STORED PROCEDURE /FUNCTION A procedure or function is a logically grouped set of SQL and PL/SQL statements that perform a specific task. To make a procedure of function, we can passed parameters before execution. 47

PROCEDURE AND FUNCTION Procedure and function are made up of: A declarative part An executable part An optional exception-handling part 48

PROCEDURE AND FUNCTION Procedure and Function are stored in Oracle Database. They can be invoked or call by any PL/SQL block. Before procedure or function is stored, the oracle engine parse and compiles the procedure or function. 49

HOW DOES THE ORACLE ENGINE CREATE A STORED PROCEDURE/FUNCTION? Few steps are performed by the oracle engine while creating a procedure. 1. Compiles the procedure or function 2. Stores the procedure of function in the database. If oracle engine compiles the PL/SQL block, if any error occurs during the compilation of procedure or function, an invalid procedure of function gets created. The oracle engine display a message after the creation that the procedure or function was created with compilation errors. 50

The compilation process does not display error message. If we want to see error message, error can be viewed using SELECT statement. SELECT * FROM USER_ERRORS; When function or procedure invoked, the oracle engine load the compiled procedure or function in a memory area called the SYSTEM GLOBAL AREA (SGA). 51

EXECUTE PROCEDURE/FUNCTION Oracle engine performs the following steps to execute a procedure or function 1. Verify user access 2. Verifies procedure of function validity. 3. Executes the procedure or function. 52

ADVANTAGE OF PROCEDURE/FUNCTION Security Procedure and Function can help to enforce data security Giving permission to users to access Procedure or Function. Performance Amount of information sent over a network is less. No compilation step is required to execute the code. 53

Memory Allocation The amount of memory used reduced because function and procedure can shared memory. Only one copy of procedure or function need to be load or used by different users. Productivity Redundant coding can be avoided, increased productivity. Integrity. Procedure or function need to tested only once that it give accurate result each time. 54

PROCEDURE VERSUS FUNCTION Function must return value. Function can return only one value, but, by defining multiple OUT parameters in a procedure, multiple values can be passed to the caller. 55

CREATING STORED PROCEDURE Syntax CREATE OR REPLACE PROCEDURE [SCHEMA] procedurename (<arguments> { IN, OUT, IN OUT},<data type>) {IS, AS} Variable declaration Constant declaration BEGIN PL/SQL statement EXCEPTION Statement END; 56

Parameter REPLACE Schema Procedure Argument IN OUT IN OUT Data type Description Recreates the procedure if it already exists. This option is used to change the definition of an existing procedure without dropping, recreating and regranting Is the schema to contain the proceduer. The oracle engine takes the default schema to be the current schema, if it is omitted Is the name of the procedure to be created Is the name of an argument to the procedure. Indicates that the parameter will accept a value from the user Indicates that the parameter will return a value to the user Indicates that the parameter will either accept a value from the user or return a value to the user Is the data type of an argument. It supports any data type supported by PL/SQL 57

EXAMPLE 58

FUNCTION Syntax CREATE OR REPLACE FUNCTION [SCHEMA] functionname (<ARGUMENT> IN <data type>) RETURN <Data type> (IS, AS) Variable declaration Constant declaration BEGIN PL/SQL statement EXCEPTION Statement END; 59

REPLACE Schema Function Argument IN RETURN DATA Type Recreates the function if already exists The oracle engine takes the default schema to be current schema, if it is omitted Is the name of function to be created Is the name of an argument to the function, parentheses can be omitted if no arguments are present. Indicates that the parameter will accept a value from the user Is the data type of function s return value. Because every function must return a value, this clause is required. 60

EXAMPLE 61

OUTPUT 62

DATABASE TRIGGERS Database triggers are database objects created via the SQL * Plus tool on the client and stored on the server. These database objects consist following distinct sections: A named database event A PL/SQL block that will execute when event occurs. 63

DATABASE TRIGGERS The oracle engine allows the definition of procedures that are implicitly executed, when an insert, update or delete is issued against a table from SQL* Plus or through an application. These procedures are called database trigger. 64

USE OF TRIGGER A trigger can also be used to keep track of a table i.e. store the modified and delete record of the table. It can be used to prevent invalid transaction. Enforce complex security authorization. 65

TRIGGERS V/S PROCEDURES Trigger do not accept parameters where as procedures can. Triggers is executed implicitly by the oracle engine To execute procedure, it has to explicitly called by a user. 66

HOW TO APPLY DATABASE TRIGGERS A trigger has three basic parts A triggering event or statement. It is a SQL statement that causes a trigger to fired. It can be INSERT, UPDATE OR DELETE statement for a specific table. A trigger restriction A trigger restriction specifies a Boolean expression that must be TRUE for the trigger to fire. A trigger restriction is specified using a WHEN clause. A trigger action A trigger action is the PL/SQL code to be executed when a triggering statement is encountered. 67

TYPES OF TRIGGERS Row Triggers:- A row trigger is fired each time a row in the table is 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. It the triggering statement affects no rows, the trigger is not executed at all. 68

STATEMENT TRIGGER A statement trigger fired once on behalf of the triggering statement. Statement trigger should be used when a triggering statement affects rows in a table but the processing required is completely independent of the number of rows affected. 69

BEFORE V/S AFTER TRIGGERS When defining a trigger it is necessary to specify the trigger timing. i.e. specify when the triggering action is to be executed in relation to the triggering statement. BEFORE and AFTER apply to both row and the statement triggers. 70

SYNTAX CREATE OR REPLACE TRIGGER TriggerName {BEFORE, AFTER} {DELETE, INSERT, UPDATE [OF COLUMN ]} ON TableName [REFERENCING { OLD AS old, NEW AS new}] [FOR EACH ROW [WHEN condition]] DECLARE <variable declaration>; <constant declaration>; BEGIN <PL/SQL subprogram body>; EXCEPTION END; 71

KEYWORDS AND PARAMETERS OR REPLACE Recreate the trigger if already exists TriggerName BEFORE AFTER DELETE INSERT UPDATE ON Is the name of the trigger to be created. Indicates that the Oracle engine fired the trigger before executing the triggering statement Indicates that the Oracle engine fired the trigger after executing the triggering statement Indicates that the Oracle engine fires the trigger whenever a DELETE statement removes a row from the table. Indicates that the Oracle engine fires the trigger whenever an INSERT statement adds a row to table. Indicates that the Oracle engine fires the trigger whenever an UPDATE statement changes a values in one of the column specified in the OF clause. Specify the schema and name of the table, which the trigger is to be created 72

REFERENCING Specifies corelation names. Correlation names can be used in the PL/SQL block and WHEN clause of row trigger to refer specifically to old and new value of the current row. The default correlation names are OLD and NEW. FOR EACH ROW WHEN Designates the trigger to be a row trigger. The Oracle engine fires a row trigger once for each row that is affected by the triggering statement and meets the optional trigger constraint defined in the WHEN clause. Specifies the trigger restriction. The trigger restriction contains a SQL condition that must be satisfied for the Oracle engine to fire the trigger. 73

EXAMPLE 74

CREATE TRIGGER AUDIT_TRAIL AFTER UPDATE OR DELETE ON PERSON FOR EACH ROW DECLARE OPER VARCHAR2(8); BEGIN IF updating THEN END IF; OPER:='UPDATE'; IF DELETING THEN END IF; OPER:='DELETE'; INSERT INTO RECORD VALUES(:OLD.P_ID,:OLD.LASTNAME,:OLD.FIRSTNAME,:OLD.ADD RESS,:OLD.CITY); END; 75

76

VIEW PROCEDURE AND FUNCTION IN ORACLE ENGINE select object_name, object_type from user_objects where object_type in ( 'PROCEDURE', 'FUNCTION' ); 77

PREPARED BY : - Chintan Shah & Pankti Dharwa Assistant Professor Shankesinh Vaghela Bapu Institute of Technology Chintan.shah84@gmail.com 78