Objectives Why PL-SQL ? Language features

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

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.
SQL*PLUS, PLSQL and SQLLDR Ali Obaidi. SQL Advantages High level – Builds on relational algebra and calculus – Powerful operations – Enables automatic.
PL/SQL.
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.
Using Oracle PL/SQL PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding constructs found in procedural languages, resulting in a structural.
PL/SQL (Embedded SQL) Introduction Benefits Basic Constructs
PL/SQL Agenda: Basic PL/SQL block structure
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
Introduction to PL/SQL Lecture 0 – Self Study Akhtar Ali.
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.
Oracle Data Definition Language (DDL)
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Session 5: Working with MySQL iNET Academy Open Source Web Development.
SQL Training Procedures & Functions. Confidential & Proprietary Copyright © 2009 Cardinal Directions, Inc. DB Procedures & Functions Procedures and Functions.
Cursor and Exception Handling By Nidhi Bhatnagar.
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
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.
LECTURE 1 INTRODUCTION TO PL/SQL Tasneem Ghnaimat.
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 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.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
PL/SQL Block Structure DECLARE - Optional Variables, cursors, user-defined exceptions BEGIN - Mandatory SQL Statements PL/SQL Statements EXCEPTIONS - Optional.
Oracle 8i Building PL/SQL Blocks. Creating PL/SQL Blocks CURSORS PROCEDURES FUNCTIONS PACKAGES TRIGGERS CURSORS PROCEDURES FUNCTIONS PACKAGES TRIGGERS.
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.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 3 Handling Data in PL/SQL Blocks.
Guide to Oracle 10g ITBIS373 Database Development Lecture 4a - Chapter 4: Using SQL Queries to Insert, Update, Delete, and View Data.
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.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
Oracle10g Developer: PL/SQL Programming1 Objectives SQL queries within PL/SQL Host or bind variables The %TYPE attribute Include queries and control structures.
CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.
A Guide to SQL, Eighth Edition Chapter Eight SQL Functions and Procedures.
PL/SQL programming Procedures and Cursors Lecture 1 [Part 2]
Introduction to PL/SQL As usual, use speaker notes for additional information!
PL/SQL INTRODUCTION.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Introduction to PL/SQL Francis Thottungal. The outline The basic PL/SQL code structure is : DECLARE -- optional, which declares and define variables,
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.
Database An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL An introduction to using Oracle PL/SQL Definition: PL/SQL.
CS422 Principles of Database Systems Oracle PL/SQL Chengyu Sun California State University, Los Angeles.
PLSQL Cont…. Most Common Oracle Data Types VARCHAR2 –Stores variable-length character data. –Takes a required parameter that specifies a maximum length.
C LANGUAGE MULITPLE CHOICE QUESTION SET-2
A Guide to SQL, Seventh Edition
PL/SQL.
Oracle11g: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
SQL PL/SQL Presented by: Dr. Samir Tartir
Working with Composite Datatypes
Sa0951a PL/SQL 1: Introduction
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
PL/SQL week10.
PRACTICE OVERVIEW PL/SQL Part - 1.
Chapter 8 Advanced SQL.
PL/SQL Declaring Variables.
Presentation transcript:

Objectives Why PL-SQL ? Language features Basic Structure of PL/SQL program Data Types Control Flow in PL-SQL Loops in PL-SQL

Why PL SQL ? PL/SQL stands for Procedural Language/SQL. PL/SQL extends SQL by adding constructs found in procedural languages like procedures, loops, variables, objects etc. Resulting a structural language that is more powerful than SQL

PL SQL, Is there any Advantage ? Server Server SQL Query1 SQL Query2 SQL Query3 SQL Query1 SQL Query2 SQL Query3 PL-SQL Block Client Client In case of SQL to send 3 queries we will need three network trips between client and server. In PL-SQL we bundle any number of queries in a block and in single network trip task is done.

Language features Supports constructs like any other 4th generation language: Variables and Data types Loops and Control statements Procedures and Functions Packages Triggers Objects Records (Its like structure in C language)

PL SQL program structure Declare <All Variables, cursors, exception etc are declared here> Begin <All programming logic , queries , program statements are written here> Exception <All Error Handling code is written here> End; --It ends the program

PL SQL nested block <<Outer Block>> Declare Begin <<Inner Block>> Exception End;

PL SQL Block Remember : Declare is optional and only required when variables need to be declared. Exception is optional and required when Error/Exception handling is done. Begin and End are mandatory as all logic and queries are written inside it. Declare Begin Exception End;

PL SQL program- Sample I BEGIN Insert into Dept values(70,’HR’,’Pune’); Insert into Dept values(80,’PSD’,’Mumbai’); Insert into Dept values(90,’ESG’,’Pune’); END; --This program will insert three records at the same time in the table dept.

PL SQL program- Sample II -- This program displays the sum of two numbers DECLARE v_num1 Number; v_num2 Number; v_sum Number; BEGIN V_num1 := &Number1; V_num2 := &Number2; V_sum := v_num1 + v_num2 ; Dbms_Output.Put_Line (‘The Sum of number is :’ || v_sum); END;

Save , Edit and Execute program Type your program in SQL * plus To save : Save <File Name> Program is saved in the bin directory to save in other folder give complete path. Eg: Save ‘C:\ESG\FirstPrg.sql’ To make changes: Edit <File Name> To edit program saved in folder other then bin Edit ‘C:\ESG\FirstPrg.Sql’ To Execute: @ File Name To execute program saved in folder other then bin. @ ‘C:\ESG\FirstPrg.Sql’

Important Keywords Following are the keywords in PL-SQL , should not be used as a variable name. DECLARE BEGIN END EXCEPTION LOOP , END LOOP IF , ELSE , ELSIF , END IF CURSOR PROCEDURE FUNCTION Cont..

Important Keywords Keywords PACKAGE TRIGGER GRANT REVOKE FOR WHILE CASE VARRAY TYPE OBJECT

Operators Important operators in PL SQL Airthmetic : ( + , - , * , /) Logical: (AND , OR , NOT) Comparison: (<=, <, >, =) Comments (Two hyphens): -- Assignment operator: In PL SQL assignment operator is := So to assign values we need to write := Examples: z := x + y z := x z := 100 name := ‘MBT’

Operators Important operators in PL SQL Line ends with operator: ; To join two strings: || To accept value: & Power ** 2**3 means 2 raise to power 3 In loop we use .. Example: For X in 1..5 means 1 to 5 Non numeric data (string or date) is written in single quote: ‘ ‘

Examples: Accept a value num1 := &Number1; At run time this will prompt as Follows Whatever value user will enter here will be assign to variable num1 Enter a value for Number1:

Accept a value Examples: Enter a value for Name: name := ‘&Name’; At run time this will prompt as Follows Whatever value user will enter here will be assign to variable name ‘ ‘ is used in case if entered data is not numeric Enter a value for Name:

Display value To display on same line: dbms_output.put() To display on new line. dbms_output.put_line() Here dbms_output is a Oracle package its like header file or library in C language. .Put and .Put_Line are functions like printf in ‘C’ language

Display value : Examples Dbms_output.put (‘Mahindra’); Dbms_output.put (‘British’); Dbms_output.put (‘Telecom’); Dbms_output.put_line(‘ ‘); It will display Mahindra British Telecom on same line. Note : On SQL prompt after Login you need to set one command to see displayed values. SET SERVEROUTPUT ON It is important that at least once you write .put_line after any number of .put functions else values are not displayed.

Display value : Examples Dbms_output.put_line (‘Mahindra’); Dbms_output.put_line (‘British’); Dbms_output.put_line (‘Telecom’); It will display Mahindra British Telecom on different lines. Note : On SQL prompt after Login you need to set one command to see displayed values. SET SERVEROUTPUT ON

DML operations in Pl-SQL All DML operations (Insert/Update/Delete /Select) are to be written in Begin part of the block. No change in the Syntax of Insert , Update and Delete , it is same as SQL. Select syntax is different then SQL , it contains INTO clause. If Select query can return more then one rows then you should always use cursors .

Select Syntax for a Single Row Query. Select column1, column2 INTO Variable1,Variable2 From Table Name Where condition ….. The only change is as many columns you want to get from the query you need to declare that many variables and use INTO clause. All other parts of query are unchanged If Where condition here is such that query will return multiple records then CURSOR should be used. Without that it will give error.

Examples Sample 1: Sample1.SQL Sample2: Sample2.SQL

Data Types in PL SQL Scalar Types Char CHAR datatype to store fixed-length character data. Maximum size = 2000 bytes Varchar2 VARCHAR2 datatype to store variable-length character . Maximum size = 4000 bytes Number Number types let you store numeric data (integers, real numbers, and floating-point numbers), represent quantities, and do calculations.

Data Types in PL SQL Scalar Types Binary_Integer The BINARY_INTEGER datatype to store signed integers (-2**31 to 2**31) Date DATE datatype to store fixed-length datetimes Long The LONG datatype to store variable-length character strings. The LONG datatype is like the VARCHAR2 datatype, except that the maximum size of a LONG value is 32760 bytes.

Data Types in PL SQL Scalar Types NChar To store multi byte fixed length character data. Its same as Char only difference is it is used to store characters of different language like Japenese , chinese etc. Number of characters it can store depend on language. NVarchar To store multi byte variable length character data. Its same as Varchar2 only difference is it is used to store characters of different language like Japenese , chinese etc.

Data Types in PL SQL Composite Types Record Table Its like structure in C Language. To be discussed in Second day session. Table Its like Array in C Language. To be discussed in detail in Second day session. This Array type is un-constrained array VArray Its like Array in C Language. To be discussed in detail in Fourth day session. This Array type is constrained array

Reference Types Data Types in PL SQL Ref Cursor Its used for dynamic cursor. To be discussed in Second day session.

Data Types in PL SQL LOB BLOB CLOB BFILE Binary Large Object A column or variable of type BLOB can store up to 4GB of binary data in each record. CLOB Character Large Object A column or variable of type CLOB can store up to 4GB of character data in each record. BFILE It can store a file of size 4GB externally outside database for each record and can refer to that from inside the database.

Data Types in PL SQL LOB Column or variable of this type can be accessed only using a Oracle package DBMS_LOB. This should be used only if required to store a large amount of data in each record of a table You should avoid making un-necessary use of LOB’s. To be discussed in last session of PL-SQL

Variable Declaration in PL SQL Variables are always declared in DECLARE section of the program. Variable Name <Data Type> Various way to declare them v_empno Number; V_ename varchar2; v_job Char(10);

Variable Declaration in PL SQL Dynamic and preferred way to declare a variable Variable Name TableName.ColName%Type v_empno Emp.Empno%Type; V_ename Emp.Ename%Type; v_deptno Dept.Deptno%Type; Advantages of declaring in above way. Variable will always have same datatype as column Any change in column will change the type of variable also, so we need not have to change and recompile the program to run.

Variable Declaration in PL SQL %RowType Variable Name TableName%RowType v_emp Emp%RowType; Advantages of declaring in above way. Variable will become like a structure variable in C (i.e. v_emp will have same structure like Emp Table) and you can refer to individual element as follows: v_emp.empno v_emp.ename v_emp.sal

Variable Declaration in PL SQL Type : You can also make your own type in program and use in the declare section to declare variable. Type t_name is Varchar2(50); -- now you can make variable of this type v_name t_name; v_name2 t_name; v_name and v_name2 both will become varchar2(50)

Examples Examples 3 and 4 are same as sample 1 and sample 2 but here we are using variable declaration style of %Type Sample 3: Sample3.SQL Sample4: Sample4.SQL Sample5: Sample5.SQL Sample6: Sample6.SQL Sample7: Sample7.SQL

Conditional Statements IF … Then … ELSE If <condition1> Then <Code> ELSIF <Condition2> Then ELSE END IF; Note here that for one IF we only need one END IF; No END IF is required for ELSIF i.e for one set of IF condition only one END IF; is required

Conditional Statements IF … Then … ELSE If v_deptno = 10 Then DBMS_OUTPUT.PUT_LINE ('Accounting'); ELSIF v_deptno = 20 Then DBMS_OUTPUT.PUT_LINE (‘ESG'); ELSE DBMS_OUTPUT.PUT_LINE (‘Invalid'); END IF;

Conditional Statements CASE : This is available from ORACLE 8i onwards only , not in ORACLE 8 and version prior to that. CASE WHEN <Variable> = <Value1> Then <Code> WHEN <Variable> = <Value2> Then ELSE END CASE;

Conditional Statements CASE : CASE When v_deptno =10 Then DBMS_OUTPUT.PUT_LINE ('Accounting'); When v_deptno =20 Then DBMS_OUTPUT.PUT_LINE (‘ESG'); ELSE DBMS_OUTPUT.PUT_LINE (‘Invalid'); END CASE;

Examples Sample8: Sample8.SQL Sample9: Sample9.SQL

TYPES OF LOOPS Simple Loop Loop Exit When <Condition> <Code> End Loop; Exit when is required to give the condition to end the loop It is pre tested as condition is checked first and then code is executed

TYPES OF LOOPS Simple Loop Loop Exit When i = 10 dbms_output.put_line (i); End Loop; --Pre Tested

TYPES OF LOOPS Simple Loop Loop <Code> Exit When <Condition> End Loop; Exit when is required to give the condition to end the loop It is post tested as condition is checked after the code is executed

TYPES OF LOOPS Simple Loop Loop dbms_output.put_line (i); Exit When i = 10 End Loop; --Post Tested

TYPES OF LOOPS While Loop While <Condition> Loop <Code> End Loop; While is required for condition to end the Loop This is also pre tested.

TYPES OF LOOPS While Loop While i < 10 Loop dbms_output.put_line (i); End Loop;

TYPES OF LOOPS FOR Loop FOR <Variable> IN <Min> .. <Max> Loop <Code> End Loop; This Loop is used when we know the number of time the loop is to be executed. This is also pre tested.

TYPES OF LOOPS FOR Loop FOR i IN 1 .. 100 Loop <Code> End Loop; This Loop will execute the given code 100 times for i = 1 to 100

TYPES OF LOOPS FOR Loop Reverse FOR i IN Reverse 1 .. 100 Loop <Code> End Loop; This Loop will execute the given code 100 times for i = 100 to 1 This is reverse i.e from last value to first value

Examples Sample12: Sample12.SQL Sample13: Sample13.SQL

Next Session : Tomorrow Cursor ,Record and Exception Thank you !! Next Session : Tomorrow Cursor ,Record and Exception