Sa0951a PL/SQL 1: Introduction

Slides:



Advertisements
Similar presentations
BD05/06 PL/SQL  Introduction  Structure of a block  Variables and types  Accessing the database  Control flow  Cursors  Exceptions  Procedures.
Advertisements

Oracle PL/SQL IV Exceptions Packages.
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.
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
1 Oracle PL/SQL III Cursors Procedures Functions iSQLplus:
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.
A Guide to SQL, Seventh Edition. Objectives Embed SQL commands in PL/SQL programs Retrieve single rows using embedded SQL Update a table using embedded.
Introduction to PL/SQL
Objectives Why PL-SQL ? Language features
PL/SQL Introduction Database 1. Practice. Sample Database The schema of the sample database is the following: Drinkers (name, occupation, birthday, salary)
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 enables us to create, organize, retrieve and maintain data stored in database it does not provide the features which a typical programming language.
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.
Oracle10g Developer: PL/SQL Programming1 Objectives Programming fundamentals The PL/SQL block Define and declare variables Initialize variables The NOT.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
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.
Program with PL/SQL Lesson 4. Writing Control Structure.
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.
PL/SQL Oracle's Database Programming Language. Remember: Set serveroutput on With serveroutput off (default) executing procedure: With serveroutput on:
PL/SQL Procedural Language / Structured Query Language.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
CIS4368: Advanced DatabaseSlide # 1 PL/SQL Dr. Peeter KirsSpring, 2003 PL/SQL.
8 1 Chapter 8 Advanced SQL Database Systems: Design, Implementation, and Management, Seventh Edition, Rob and Coronel.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
Database Application Development using PL/SQL Programming.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
Database Management COP4540, SCS, FIU Oracle PL/SQL (Ch 10.5)
1 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
Copyright  Oracle Corporation, All rights reserved. 16 Declaring Variables.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
Introduction to PL/SQL As usual, use speaker notes for additional information!
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Advanced SQL: Cursors & Stored Procedures Instructor: Mohamed Eltabakh 1.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
1 Section 10 - Embedded SQL u Many computer languages allow you to embed SQL statements within the code (e.g. COBOL, PowerBuilder, C++, PL/SQL, etc.) u.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
ITEC 224 Database Programming
A Guide to SQL, Seventh Edition
Program with PL/SQL Lesson 4.
Creating Stored Procedures and Functions
Difference between Oracle PL/SQL and MySQL
Interacting with the Oracle Server
Fundamentals of PL/SQL part 1 (Basics)
PL/SQL.
Oracle11g: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
Oracle9i Developer: PL/SQL Programming Chapter 3 PL/SQL Processing.
Introduction to PL/SQL
Error Handling Summary of the next few pages: Error Handling Cursors.
PL/SQL – Session 1 of 4 Instructor: Jim Cody
PL/SQL Scripting in Oracle:
More SQL Nested and Union queries, and more
Chapter 4: Introduction to PL/SQL
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
PL/SQL week10.
PL/SQL Declaring Variables.
Presentation transcript:

Sa0951a PL/SQL 1: Introduction iSQLplus: http://uadisq01.uad.ac.uk:5560/isqlplus/ Sa0951a PL/SQL 1: Introduction An introduction to the procedural language in Oracle

Contents What is PL/SQL? Purpose – what is it for? Block structure Anonymous blocks Main features rules Variables and data types Loops, branching Lots of examples November 18

What is PL/SQL? Oracle's procedural programming language extension to SQL SQL is embedded in PL/SQL Very powerful We’re scratching the surface today but hang on as we go deeper over the next few weeks We shall be writing code structures called PROCEDURES, FUNCTIONS, TRIGGERS, CURSORS November 18

A very short introduction: Variables, constants: Used to temporarily store information Loops: tell Oracle to repeat an action – x times, or until some goal has been reached Conditional branching: IF statements tell Oracle to do different things depending on some condition Functions: stored programs that perform a specific action. E.g. output a value, calculate something November 18

PL/SQL Blocks A PL/SQL program is also called a Block Anonymous block: Embedded in application program, stored as script file or typed in directly Not stored by DB Named block: Can be stored Procedures, functions are examples November 18

Some PL/SQL rules Don’t abbreviate keywords Put spaces after and between keywords Each PL/SQL statement ends with a semi-colon (;) SQL takes the same form as outside of PL/SQL There is no case-sensitivity (except inside quotes) Blocks can be nested up to 200 deep – good luck! Good practice to indent nested code though not a syntactical requirement November 18

Block structure [DECLARE] declare variables and constants BEGIN lists executable statements [EXCEPTION] error handling section END; ends the block Declarations and exceptions are optional Need to add a forward slash ( / ) at end on new line to force execution November 18

Variables and Constants Defined in DECLARE statement This creates spaces in memory for temporary storage of data of a specific type Constant values are fixed. Variables can of course vary during execution! November 18

Defining variables and constants Variable_name datatype; Variable_name datatype := expression or value; Variable_name datatype NOT NULL := expression or value; Are set to NULL by default Constants constant_name CONSTANT datatype := expression or value; November 18

Example Block 1_1 DECLARE v_surname varchar2(20); v_salary number(9,2):=0; v_tax number(9,2):=ROUND(v_salary*0.25,2); v_snum number(4) NOT NULL :=0; c_tax1 CONSTANT number(3,2) := 0.10; c_tax2 CONSTANT number(3,2) := 0.23; BEGIN v_snum := v_salary - v_tax; END; / This works but gives no output, neither stores result November 18

Some Rules Each statement ends with semi-colon; Variable names are not case sensitive and may be up to 30 characters long Expressions can contain references to previously defined variables or constants in the current DECLARE section Forward references are NOT allowed Each variable or constant name in the same block must be unique November 18

Anchoring data types: %TYPE Generally ……. v_varname table.column%type; c_constname CONSTANT table.column%type := expression; DECLARE v_surname personnel.SURNAME%TYPE; v_bonus personnel.BONUS%TYPE; BEGIN ……………….. This allows a variable or constant to take on the same datatype as an attribute already defined in a table November 18

Displaying output with DBMS_OUTPUT and PUT_LINE Block 1_2 Displaying output with DBMS_OUTPUT and PUT_LINE SET SERVEROUTPUT ON DECLARE v_surname varchar2(20):= 'BROWN'; v_salary number(9,2) := 10000; BEGIN DBMS_OUTPUT.PUT_LINE('Print these details'); DBMS_OUTPUT.PUT_LINE('-------------------'); DBMS_OUTPUT.PUT_LINE(v_surname||' earns '||v_salary); DBMS_OUTPUT.PUT_LINE('+++++++++++++++++++'); END; / PL/SQL procedure successfully completed. November 18

November 18 The NULL statement Performs a null operation (i.e. nothing) and is a useful command to have while developing and testing code (i.e. a placeholder) Begin ... IF v_salary > 30000 THEN NULL; -- write this later END IF; END; / The NULL statement November 18 (c) CATS, University of Abertay Dundee

Prompting for a value Block 1_2a DECLARE v_divname branch.divname%Type; v_surname personnel.surname%Type := UPPER('&surname'); BEGIN DBMS_OUTPUT.PUT_LINE('converted to: '||v_surname); END; / The program will pause when it encounters the “&” character and prompt for a surname November 18

Ok – spot the errors block 1_3 DECLARE v_surname varchar2(10); v_N1 number=23.4567; v_joindate date v_incep date:="28-Jan-67"; v_N2 number:=SQRT(Round(v_N1/3.4,2)); v_maxbonus number(3,2):= 300.67; v_stockout bolean:=false; BEGIN NULL; -- develop associated code later END / November 18

SELECT ….. INTO ……… One of the key issues of PL/SQL is to extract data from a database to perform some other process SELECT <attribute(s)> INTO variable FROM <table(s)> WHERE <condition> … Variable MUST be declared prior to use November 18

Example (only works for 1 row!) block 1_4 Example (only works for 1 row!) DECLARE v_surname personnel.surname%type; v_bonus personnel.bonus%type; BEGIN SELECT surname, bonus*1.15 INTO v_surname, v_bonus FROM PERSONNEL WHERE SNUM = 3200; DBMS_OUTPUT.PUT_LINE(v_surname||' earns ' ||v_bonus); END; / Note the single ; at end of SQL code Would output - “RAINES earns 575” November 18

Fuller Example DECLARE qty_on_hand NUMBER(6); BEGIN SELECT quantity INTO qty_on_hand FROM inventory WHERE product = 'golf club'; IF qty_on_hand > 0 THEN UPDATE inventory SET quantity = quantity - 1 WHERE product='golf club'; DBMS_output.put_line('in stock: '||qty_on_hand); INSERT INTO purchase_log VALUES('Golf club purchased', SYSDATE); ELSE VALUES('out of golf clubs', SYSDATE); END IF; COMMIT; END; / Looks up quantity of golf clubs from inventory table and assigns to variable Checks > 0 Reduce quantity by 1 Record a message in the purchase log of zero stock November 18

LOOPS 3 types: For Loop While Loop Simple or Infinite Loop November 18

FOR Loop TEST BEGIN FOR v_count IN 1..10 LOOP Insert into test(id_no) values(v_count); END LOOP; END; / ID_NO 1 2 3 4 5 6 7 8 9 10 Notes: v_count is NOT declared -- it is implicit The table test with column id_no must exist November 18

While Loop WHILE LOOP Block 1_5 To test: Select * from Test Run program While Loop TEST DECLARE V_count number(2):=1; BEGIN WHILE v_count < 11 LOOP Insert into test(id_no) values(v_count); v_count:=v_count+1; END LOOP; END; / WHILE LOOP ID_NO 1 2 3 4 5 6 7 8 9 10 November 18

Infinite Loop Example TEST DECLARE V_count number(2):=1; BEGIN LOOP Insert into test(id_no) values(v_count); EXIT WHEN v_count=10; v_count:=v_count+1; END LOOP; END; / ID_NO 1 2 3 4 5 6 7 8 9 10 November 18

IF…THEN…ELSIF…ELSE IF condition THEN statement(s); [ELSIF condition THEN statement(s);] [ELSE statement(s);] END IF; Note: Yes, it is ELSIF, not ELSEIF and not ELSE IF November 18

If Example Block 1_6 To test: Select * from Test Run block TEST DECLARE v_count number(2):=1; BEGIN LOOP IF v_count between 1 and 5 THEN Insert into test values (v_count, 'Group1'); ELSIF v_count between 6 and 10 THEN Insert into test values (v_count, 'Group2'); ELSE Insert into test values (v_count, 'Group3'); END IF; EXIT WHEN v_count =15; v_count:=v_count+1; END LOOP; END; / TEST ID_NO DETAILS 1 GROUP1 2 GROUP1 3 GROup1 4 GROUP1 5 GROUP1 6 GROUP2 7 GROUP2 9 GROUP2 10 GROUP2 11 GROUP3 … November 18

Summary and look Ahead Looked at Classical programming structures: Loops, Ifs etc Anchoring data types Block structure: Declare …. Begin…… Exception … End; Variables and constants Going to look at Exception handling, cursors, procedures, functions, triggers, packages hopefully! November 18

Some other useful examples… Some other useful examples….. <<Labels>> (useful when nesting) BEGIN <<firstloop>> FOR counter in 1..2 Loop DBMS_OUTPUT.PUT_LINE('1st: '||firstloop.counter); <<secondloop>> FOR counter in 1..4 Loop DBMS_OUTPUT.PUT_LINE('1st: '|| firstloop.counter); DBMS_OUTPUT.PUT_LINE('2nd: '|| secondloop.counter); END LOOP secondloop; -- aids readability DBMS_OUTPUT.PUT_LINE('--------------------'); END LOOP firstloop; -- aids readability END; / November 18

IF: Conditional Tests supported Logicals: AND OR NOT Expressions: IS [NOT] NULL, [NOT] BETWEEN a AND b [NOT] like a, [NOT] IN list Comparisons: < > <= >= <> != Operations: + - * / (and more) Functions: any legal SQL function November 18

Reading & References Connolly/Begg (3rd/4th ed) Section 8.2.5 Oracle® PL/SQL™ by Example – in Safari e-books Morris-Murphy chapters 15 & 16 Shah, N. (2002). Database Systems Using Oracle. A simplified guide to SQL and PL/SQL. Chapter 8 onwards Morrison/Morrison Chapter 4. November 18