Sisteme Informatice şi Standarde Deschise (SISD) Curs 7 Standarde pentru programarea bazelor de date (1)

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

Database Programming with PL/SQL

Database Programming with PL/SQL

UNIT II PL / SQL AND TRIGGERS

PL/SQL Block structure

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

Contents I Introduction 1 Introduction to PL/SQL iii

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

ORACLE: PL/SQL Programming

Question Bank PL/SQL Fundamentals-I

PLSQL Interview Questions :

Oracle Class VI. Exception Block Cursors For Loops

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

Database Programming with PL/SQL

Writing Control Structures

Section I : Section II : Question 1. Question 2. Question 3.

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

Oracle PLSQL. Course Summary. Duration. Objectives

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

Oracle Database 11g: PL/SQL Fundamentals

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

Introduction to Computer Science and Business

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

Oracle Database: Introduction to SQL/PLSQL Accelerated

Oracle Database: Program with PL/SQL

Oracle Database: Program with PL/SQL Ed 2

RNDr. Michal Kopecký, Ph.D. Department of Software Engineering, Faculty of Mathematics and Physics, Charles University in Prague

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.

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

Oracle PLSQL Training Syllabus

Database Programming with PL/SQL

Procedural Language Structured Query Language (PL/SQL)

Introduction to SQL/PLSQL Accelerated Ed 2

PLSQL 9i Index. Section Title Page

Database Programming with PL/SQL

Manipulating Data. Copyright 2004, Oracle. All rights reserved.

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

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

Database Foundations. 6-4 Data Manipulation Language (DML) Copyright 2015, Oracle and/or its affiliates. All rights reserved.

KATHERYNE MERIVETH AMARO MEDRANO. this Student Guide

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

Meet MariaDB Vicențiu Ciorbaru Software MariaDB Foundation * * 2017 MariaDB Foundation

Oracle Database 11g: SQL and PL/SQL Fundamentals

Database Programming with PL/SQL

Oracle Database: SQL and PL/SQL Fundamentals NEW

Slides by: Ms. Shree Jaswal

Oracle Database: SQL and PL/SQL Fundamentals Ed 2

Oracle TimesTen In-Memory Database

Oracle TimesTen In-Memory Database

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

REF Cursors. Oracle University and Egabi Solutions use only

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

ORACLE Job Placement Paper. Paper Type : General - other

5. Single-row function

Oracle Database 11g: Program with PL/SQL

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

Oracle Internal & Oracle Academy

Table of Contents. Oracle SQL PL/SQL Training Courses

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

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

Data Manipulation Language

Sisteme Informatice şi Standarde Deschise (SISD) Curs 8 Standarde pentru programarea bazelor de date (2)

PL/SQL. Exception. When the PL/SQL engine cannot execute the PLSQL block it raise an error. Every Oracle error has an error number

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

Database Programming with PL/SQL

SELF TEST. List the Capabilities of SQL SELECT Statements

IT Certification Exams Provider! Weofferfreeupdateserviceforoneyear! h ps://

Oracle 1z z0-146 Oracle Database 11g: Advanced PL/SQL. Practice Test. Version QQ:

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

Oracle Introduction to PL/SQL

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

Introduction to Oracle9i: SQL

Appendix A Practices and Solutions

Lecture 08. Spring 2018 Borough of Manhattan Community College

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

Lab Assignment 9 CIS 208A PL/SQL Programming and SQL

Táblák tartalmának módosítása. Copyright 2004, Oracle. All rights reserved.

Oracle PL/SQL Best Practices Part 1. John Mullins

7. PL/SQL. 7.1 Introduction. PL/SQL = Procedural Language extensions to SQL

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

M.SC(IT) I YEAR( ) CORE: ADVANCED DBMS-163B Semester : I Multiple Choice Questions

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

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

PL / SQL Basics. Chapter 3

Course 492 Supplementary Materials. Mutating Tables

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

Denys Xavier denys org br) has a non-transferable license to use this Student Guide

RETRIEVING DATA USING THE SQL SELECT STATEMENT

BraindumpsVCE. Best vce braindumps-exam vce pdf free download

1Z0-144.v Number: 1Z0-144 Passing Score: 800 Time Limit: 120 min File Version:

5 Integrity Constraints and Triggers

to use this Student Guide

Database Programming with PL/SQL

Oracle 1Z Oracle Database 11g : SQL Fundamentals I. Download Full Version :

PL/SQL User s Guide and Reference

Oracle EXAM 1Z0-144 Oracle Database 11g: Program with PL/SQL

RDBMS Using Oracle. Use of IN OUT

The following practical s have to be performed and journal should contain the output with aim as per syllabus. This is just for reference

ORACLE DATABASE 12C INTRODUCTION

Transcription:

Administrarea Bazelor de Date Managementul în Tehnologia Informaţiei Sisteme Informatice şi Standarde Deschise (SISD) 2009-2010 Curs 7 Standarde pentru programarea bazelor de date (1) 23.11.2009 Sisteme Informatice şi Standarde Deschise Curs 7 1

Re-visiting SQL Instructions to Oracle identifying the information you wish to select, insert, delete or update SQL*Plus is Oracle's version of the SQL standard 2

PL/SQL - Introduction Procedural extension allowing for modularity, variable declaration, loops and logical constructs. Allows for advanced error handling Communicates natively with other oracle database objects. Managed centrally within the Oracle database. Why use PL/SQL Manage business rules through middle layer application logic. Generate code for triggers Generate code for interface Enable database-centric client/server applications 3

Centralised V s De-centralised Begin : End; Begin : End; Begin : End; Server Begin : End; Common copy of executed code one copy to maintain Multiple copies of executable code on the decentralised system multiple copies to maintain leading to increase difficulty in maintaining the system Server 4

Advantages of using PL/SQL to access Oracle PL/SQL is managed centrally within the database Code is managed by the DBA and execution privileges are managed in the same was as with other objects PL/SQL objects are first-class Oracle DB objects Easy to read With modularity features and error handling 5

Enables DBA to: Centralised control Specify rules in one place (as procedure, function, package in PL/SQL) Force user access through the predefined PL/SQL so users cannot write their own procedural code and use this instead. Define for instance security privileges giving users access to table(s) only through a particular procedure 6

Using PL/SQL as a programming language Permits all operations of standard programming languages e.g. Conditions IF-THEN-ELSE-END IF; Jumps GOTO Provides loops for controlling iteration LOOP-EXIT; WHEN-END LOOP; FOR-END LOOP; WHILE-END LOOP Allows extraction of data into variables and its subsequent manipulation 7

Human Resources (HR) Schema 8

Review of PL/SQL Block Structure for Anonymous PL/SQL Blocks DECLARE (optional) Declare PL/SQL objects to be used within this block BEGIN (mandatory) Define the executable statements EXCEPTION (optional) Define the actions that take place if an error or exception arises END; (mandatory) 9

Syntax: Examples: Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare Declaring PL/SQL Variables identifier [CONSTANT] datatype [NOT NULL] [:= DEFAULT expr]; Declare v_hiredate DATE; v_deptno NUMBER(2) NOT NULL := 10; v_location VARCHAR2(13) := 'Atlanta'; c_ comm CONSTANT NUMBER := 1400; v_count BINARY_INTEGER := 0; v_valid BOOLEAN NOT NULL := TRUE; 10

Declaring Variables with the %TYPE Attribute Examples:... v_ename employees.last_name%type; v_balance NUMBER(7,2); v_min_balance v_balance%type := 10;... 11

Creating a PL/SQL Record Declare variables to store the name, job, and salary of a new employee. Example:... TYPE emp_record_type IS RECORD (ename VARCHAR2(25), job VARCHAR2(10), sal NUMBER(8,2)); emp_record emp_record_type;... 12

%ROWTYPE Attribute Examples: Declare a variable to store the same information about a department as is stored in the DEPARTMENTS table. dept_record departments%rowtype; Declare a variable to store the same information about an employee as is stored in the EMPLOYEES table. emp_record employees%rowtype; 13

Creating a PL/SQL Table DECLARE TYPE ename_table_type IS TABLE OF employees.last_name%type INDEX BY BINARY_INTEGER; TYPE hiredate_table_type IS TABLE OF DATE INDEX BY BINARY_INTEGER; ename_table ename_table_type; hiredate_table hiredate_table_type; BEGIN ename_table(1) := 'CAMERON'; hiredate_table(8) := SYSDATE + 7; IF ename_table.exists(1) THEN INSERT INTO...... END; 14

SELECT Statements in PL/SQL The INTO clause is mandatory. Example: DECLARE v_deptid NUMBER(4); v_loc NUMBER(4); BEGIN SELECT department_id, location_id INTO v_deptno, v_loc FROM departments WHERE department_name = 'Sales';... END; 15

Inserting Data Add new employee information to the EMPLOYEES table. Example: DECLARE v_empid employees.employee_id%type; BEGIN SELECT employees_seq.nextval INTO v_empno FROM dual; INSERT INTO employees(employee_id, last_name, job_id, department_id) VALUES(v_empno, 'HARDING', 'PU_CLERK', 30); END; 16

Updating Data Increase the salary of all employees in the EMPLOYEES table who are purchasing clerks. Example: DECLARE v_sal_increase employees.salary%type := 2000; BEGIN UPDATE employees SET salary = salary + v_sal_increase WHERE job_id = 'PU_CLERK'; END; 17

Deleting Data Delete rows that belong to department 190 from the EMPLOYEES table. Example: DECLARE v_deptid employees.department_id%type := 190; BEGIN DELETE FROM employees WHERE department_id = v_deptid; END; 18

COMMIT and ROLLBACK Statements Initiate a transaction with the first DML command to follow a COMMIT or ROLLBACK statement. Use COMMIT and ROLLBACK SQL statements to terminate a transaction explicitly. 19

SQL Cursor Attributes Using SQL cursor attributes, you can test the outcome of your SQL statements. SQL%ROWCOU NT SQL%FOUND SQL%NOTFOUN D SQL%ISOPEN Number of rows affected by the most recent SQL statement (an integer value) Boolean attribute that evaluates to TRUE if the most recent SQL statement affects one or more rows Boolean attribute that evaluates to TRUE if the most recent SQL statement does not affect any rows Always evaluates to FALSE because PL/SQL closes implicit cursors immediately after they are executed 20

IF, THEN, and ELSIF Statements For a given value entered, return a calculated value. Example:... IF v_start > 100 THEN v_start := 2 * v_start; ELSIF v_start >= 50 THEN v_start := 0.5 * v_start; ELSE v_start := 0.1 * v_start; END IF;... 21

Basic Loop Example: DECLARE v_ordid order_items.order_id%type := 101; v_counter NUMBER(2) := 1; BEGIN LOOP INSERT INTO order_items(order_id,line_item_id) VALUES(v_ordid, v_counter); v_counter := v_counter + 1; EXIT WHEN v_counter > 10; END LOOP; END; 22

FOR Loop Insert the first 10 new line items for order number 101. Example: DECLARE v_ordid order_items.order_id%type := 101; BEGIN FOR i IN 1..10 LOOP INSERT INTO order_items(order_id,line_item_id) VALUES(v_ordid, i); END LOOP; END; 23

WHILE Loop Example: ACCEPT p_price PROMPT 'Enter the price of the item: ' ACCEPT p_itemtot - PROMPT 'Enter the maximum total for purchase of item: ' DECLARE... v_qty NUMBER(8) := 1; v_running_total NUMBER(7,2) := 0; BEGIN... WHILE v_running_total < &p_itemtot LOOP... v_qty := v_qty + 1; v_running_total := v_qty * &p_price; END LOOP;... 24

Controlling Explicit Cursors No DECLARE OPEN FETCH EMPTY? Yes CLOSE Create a named SQL area Identify the active set Load the current row into variables Test for existing rows Return to FETCH if rows found Release the active set 25

Declaring the Cursor Example: DECLARE CURSOR c1 IS SELECT employee_id, last_name FROM employees; CURSOR c2 IS SELECT * FROM departments WHERE department_id = 10; BEGIN... 26

Opening the Cursor Syntax: OPEN cursor_name; Open the cursor to execute the query and identify the active set. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch. 27

Examples: Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare Fetching Data from the Cursor FETCH c1 INTO v_empid, v_ename;... OPEN defined_cursor; LOOP FETCH defined_cursor INTO defined_variables EXIT WHEN...;... -- Process the retrieved data... END; 28

Closing the Cursor Syntax: CLOSE cursor_name; Close the cursor after completing the processing of the rows. Reopen the cursor, if required. Do not attempt to fetch data from a cursor after it has been closed. 29

Explicit 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 30

Cursor FOR Loops Retrieve employees one by one until there are no more left. Example: DECLARE CURSOR c1 IS SELECT employee_id, last_name FROM employees; BEGIN FOR emp_record IN c1 LOOP -- implicit open and implicit fetch occur IF emp_record.employee_id = 134 THEN... END LOOP; -- implicit close occurs END; 31

FOR UPDATE Clause Retrieve the orders for amounts over $1,000 that were processed today. Example: DECLARE CURSOR c1 IS SELECT customer_id, order_id FROM orders WHERE order_date = SYSDATE AND order_total > 1000.00 ORDER BY customer_id FOR UPDATE NOWAIT; 32

WHERE CURRENT OF Clause Example: DECLARE CURSOR c1 IS SELECT salary FROM employees FOR UPDATE OF salary NOWAIT; BEGIN... FOR emp_record IN c1 LOOP UPDATE... WHERE CURRENT OF c1;... END LOOP; COMMIT; END; 33

Trapping Predefined Oracle Server Errors Reference the standard name in the exception-handling routine. Sample predefined exceptions: NO_DATA_FOUND TOO_MANY_ROWS INVALID_CURSOR ZERO_DIVIDE DUP_VAL_ON_INDEX 34

Syntax: Universitatea Politehnica Bucureşti - Facultatea de Automatica si Calculatoare Trapping Predefined Oracle Server Errors: Example BEGIN SELECT... COMMIT; EXCEPTION WHEN NO_DATA_FOUND THEN statement1; statement2; WHEN TOO_MANY_ROWS THEN statement1; WHEN OTHERS THEN statement1; statement2; statement3; END; 35

Non-Predefined Error Trap for Oracle server error number 2292, which is an integrity constraint violation. DECLARE e_products_invalid EXCEPTION; PRAGMA EXCEPTION_INIT ( e_products_invalid, -2292); v_message VARCHAR2(50); BEGIN... EXCEPTION WHEN e_products_invalid THEN :g_message := 'Product ID specified is not valid.';... END; 3 1 2 36

User-Defined Exceptions Example: [DECLARE] e_amount_remaining EXCEPTION;... BEGIN... RAISE e_amount_remaining;... EXCEPTION WHEN e_amount_remaining THEN :g_message := 'There is still an amount in stock.';... END; 1 2 3 37

RAISE_APPLICATION_ERROR Procedure Syntax: raise_application_error (error_number, message[, {TRUE FALSE}]); Enables you to issue user-defined error messages from stored subprograms Called from an executing stored subprogram only 38

RAISE_APPLICATION_ERROR Procedure Used in two different places: Executable section Exception section Returns error conditions to the user in a manner consistent with other Oracle server errors 39

Exam s quizzes 1. Care sunt principalele avantaje ale utilizării PL/SQL? 2. Ce sunt Cursoarele SQL şi care este modul lor de control? 40