PL/SQL.

Slides:



Advertisements
Similar presentations
PL/SQL.
Advertisements

Programming Languages and Paradigms The C Programming Language.
AN INTRODUCTION TO PL/SQL Mehdi Azarmi 1. Introduction PL/SQL is Oracle's procedural language extension to SQL, the non-procedural relational database.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
PL/SQL (Procedural Language extensions to SQL) Prepared by: Manoj Kathpalia Edited by: M V Ramakrishna.
Chapter 10.
Lecture-5 Though SQL is the natural language of the DBA, it suffers from various inherent disadvantages, when used as a conventional programming language.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
JavaScript, Fourth Edition
Introduction to PL/SQL
Chapter 2: Introduction to C++.
JavaScript, Third Edition
VB .NET Programming Fundamentals
String Escape Sequences
1 Introduction to PL/SQL. 2  Procedural programming language  Uses detailed instructions  Processes statements sequentially  Combines SQL commands.
2440: 211 Interactive Web Programming Expressions & Operators.
Chapter 10 Selected Single-Row Functions Oracle 10g: SQL.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Oracle10g Developer: PL/SQL Programming1 Objectives Programming fundamentals The PL/SQL block Define and declare variables Initialize variables The NOT.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
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.
BASICS CONCEPTS OF ‘C’.  C Character Set C Character Set  Tokens in C Tokens in C  Constants Constants  Variables Variables  Global Variables Global.
PL/SQL Declaring Variables PL/SQL Block Structure DECLARE (Optional) Variables, cursors, user-defined exceptions BEGIN (Mandatory) - SQL statements -
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.
1 PL/SQLPL/SQL Declaring Variables Declaring Variables Declaring Variables Declaring Variables Writing Executable Statements Writing Executable Statements.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 2 Variables.
1 Scripting Languages VBScript - Recognized mainly by Internet Explorer only - Netscape does have a plug-in JavaScript - Recognized by Internet Explorer.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Introduction to Scripting.
Part:2.  Keywords are words with special meaning in JavaScript  Keyword var ◦ Used to declare the names of variables ◦ A variable is a location in the.
CHAPTER 2 PROBLEM SOLVING USING C++ 1 C++ Programming PEG200/Saidatul Rahah.
2: Basics Basics Programming C# © 2003 DevelopMentor, Inc. 12/1/2003.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 2 Introduction to C++
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Java Basics. Tokens: 1.Keywords int test12 = 10, i; int TEst12 = 20; Int keyword is used to declare integer variables All Key words are lower case java.
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
C LANGUAGE MULITPLE CHOICE QUESTION SET-2
Definition of the Programming Language CPRL
Chapter 6 JavaScript: Introduction to Scripting
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Oracle11g: PL/SQL Programming Chapter 2 Basic PL/SQL Block Structures.
Programming Languages and Paradigms
Multiple variables can be created in one declaration
Programming Paradigms
2.1 Parts of a C++ Program.
Introduction to C++ Programming
Chapter 8 JavaScript: Control Statements, Part 2
Chapter 4: Introduction to PL/SQL
elementary programming
Chapter 2: Introduction to C++.
PL/SQL Declaring Variables.
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
In this class, we will cover:
Unit 3: Variables in Java
Programming Languages and Paradigms
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

PL/SQL

PL/SQL PL/SQL is a combination of SQL along with the procedural features of programming languages. It was developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL

PL/SQL PL/SQL programs are divided into 3 block 1 Declarations 2 Executable Commands 3 Exception Handling Every PL/SQL statement ends with a semicolon (;)

PL/SQL 1 Declarations This section starts with the keyword DECLARE. It is an optional section and defines all variables, cursors, subprograms, and other elements to be used in the program. 2 Executable Commands  This section is enclosed between the keywords BEGIN and END and it is a mandatory section. It consists of the executable PL/SQL statements of the program. 3 Exception Handling  This section starts with the keyword EXCEPTION. This section is optional and contains exception(s) that handle errors in the program.

PL/SQL syntax DECLARE <declarations section> BEGIN <executable command(s)> EXCEPTION <exception handling> END;

PL/SQL Example DECLARE message varchar2(20):='popo'; BEGIN dbms_output.put_line(message); END; / To display the message set serveroutput on;

PL/SQL The PL/SQL Delimiters A delimiter is a symbol with a special meaning. Delimiter Description +, -, *, / Addition, subtraction/negation, multiplication, division % Attribute indicator ' Character string delimiter . Component selector (,) Expression or list delimiter : Host variable indicator , Item separator " Quoted identifier delimiter = Relational operator @ Remote access indicator

PL/SQL The PL/SQL Delimiters A delimiter is a symbol with a special meaning. Delimiter Description ; Statement terminator := Assignment operator => Association operator || Concatenation operator ** Exponentiation operator <<, >> Label delimiter (begin and end) /*, */ Multi-line comment delimiter (begin and end) -- Single-line comment indicator .. Range operator <, >, <=, >= Relational operators <>, '=, ~=, ^= Different versions of NOT EQUAL

PL/SQL The PL/SQL Comments single-line and multi-line comments. All characters available inside any comment are ignored by PL/SQL compiler. The PL/SQL single-line comments start with the delimiter --(double hyphen) and Multi-line comments are enclosed by /* and */.

PL/SQL Example DECLARE --variable declaration message varchar2(20):= 'popo'; BEGIN /* PL/SQL excecutable statments */ dbms_output.put_line(message); END; /

PL/SQL PL/SQL - Data Types SCALAR Large Object (LOB) Composite Reference

PL/SQL PL/SQL - Data Types Scalar Large Object (LOB) Composite Category Description Scalar Single values, such as a NUMBER, DATE, or BOOLEAN. Large Object (LOB) Pointers to large objects that are stored separately from other data items, such as text, graphic images, video clips, and sound waveforms. Composite Data items that have internal components that can be accessed individually. For example, collections and records. Reference Pointers to other data items.

PL/SQL PL/SQL - Data Types Scalar Data Type Date Type Description Numeric Numeric values on which arithmetic operations are performed. Character Alphanumeric values that represent single characters or strings of characters. Boolean Logical values on which logical operations are performed. Datetime Dates and times.

PL/SQL PL/SQL - Data Types Scalar Data Type PL/SQL Numeric Data Type Description NUMBER(prec, scale) Fixed-point or floating-point number with absolute value in range 1E-130 to (but not including) 1.0E126. A NUMBER variable can also represent 0. DECIMAL(prec, scale) IBM specific fixed-point type with maximum precision of 38 decimal digits. NUMERIC(pre, secale) Floating type with maximum precision of 38 decimal digits. DOUBLE PRECISION ANSI specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits)

PL/SQL PL/SQL - Data Types Scalar Data Type PL/SQL Numeric Data Type Description FLOAT ANSI and IBM specific floating-point type with maximum precision of 126 binary digits (approximately 38 decimal digits) INT ANSI specific integer INTEGER ANSI and IBM specific integer type REAL Floating-point type with maximum precision of 63 binary digits (approximately 18 decimal digits)

PL/SQL Example DECLARE a integer; b integer; BEGIN a:=10; b:=20; dbms_output.put_line('value of a '||a); dbms_output.put_line('value of b '||b); END; /

PL/SQL PL/SQL - Data Types Scalar Data Type Character Data Type Description CHAR Fixed-length character string with maximum size of 32,767 bytes VARCHAR2 Variable-length character string with maximum size of 32,767 bytes NCHAR Fixed-length national character string with maximum size of 32,767 bytes NVARCHAR2 Variable-length national character string with maximum size of 32,767 bytes LONG Variable-length character string with maximum size of 32,760 bytes ROWID Physical row identifier, the address of a row in an ordinary table

PL/SQL PL/SQL - Data Types Scalar Data Type Boolean Data Type  Boolean values TRUE and FALSE and the value NULL.

PL/SQL PL/SQL - Data Types Scalar Data Type Datetime and Interval Type Each DATE includes the century, year, month, day, hour, minute, and second. The following table shows the valid values for each field:

PL/SQL PL/SQL - Data Types Scalar Data Type Datetime and Interval Type Field Name Valid Datetime Values Valid Interval Values YEAR -4712 to 9999 (excluding year 0) Any nonzero integer MONTH 01 to 12 0 to 11 DAY 01 to 31 (limited by the values of MONTH and YEAR, according to the rules of the calendar for the locale) HOUR 00 to 23 0 to 23 MINUTE 00 to 59 0 to 59 SECOND 00 to 59.9(n), where 9(n) is the precision of time fractional seconds 0 to 59.9(n), where 9(n) is the precision of interval fractional seconds

PL/SQL PL/SQL - Data Types Scalar Data Type Large Object (LOB) Data Type Data Type Description Size BFILE Used to store large binary objects in operating system files outside the database. System-dependent. Cannot exceed 4 gigabytes (GB). BLOB Used to store large binary objects in the database. 8 to 128 terabytes (TB) CLOB Used to store large blocks of character data in the database. 8 to 128 TB NCLOB Used to store large blocks of NCHAR data in the database.

PL/SQL PL/SQL - Variables Name given to a storage area that our programs can manipulate. Each variable in PL/SQL has a specific data type, which determines the size and layout of the variable's memory; Syntax : Variable Declaration in PL/SQL variable_name [CONSTANT] datatype [NOT NULL] [:= DEFAULT initial_value] example a number(10, 2); pi constant double precision := 3.1415; name varchar2(25);

PL/SQL Initializing Variables in PL/SQL Whenever declare a variable, PL/SQL assigns it a default value of NULL. If we want to initialize a variable with a value other than the NULL value, Using either of the following: The DEFAULT keyword The assignment operator (:=) For example: C integer := 0; message varchar2(20) DEFAULT 'Have a Good Day';

PL/SQL Example DECLARE a integer:=10; b integer:=20; c integer; d real; BEGIN c:=a+b; d:=a/b; dbms_output.put_line('sum= '||c); dbms_output.put_line('division= '||d); END; / Output Sum=30 Division=.5

PL/SQL Scope of a variable PL/SQL allows the nesting of Blocks, i.e., Each program block may contain another inner block. If a variable is declared within an inner block, it is not accessible to the outer block. A variable is declared and accessible to an outer Block, it is also accessible to all nested inner Blocks. There are two types of variable scope: Local variables - variables declared in an inner block and not accessible to outer blocks. Global variables - variables declared in the outermost block or a package.

PL/SQL Example DECLARE -- global variable global integer:=10; BEGIN dbms_output.put_line('global= '||global); --Local Variable local integer:=20; dbms_output.put_line('local='||local); dbms_output.put_line('global='||global); END ; END; / Output Global =10 Local=20 Global=10

PL/SQL declare r tab1.rollno%type:=1; n tab1.name%type; begin Assigning SQL Query Results to PL/SQL Variables Using SELECT INTO statement of SQL to assign values to PL/SQL variables. Example Table tab1(rollno,name) declare r tab1.rollno%type:=1; n tab1.name%type; begin select rollno,name into r,n from tab1 where rollno=r; dbms_output.put_line(‘Roll='||r); dbms_output.put_line(‘Name='||n); end; / Output Roll=1 Name=aji rollno name 1 aji 2 saji

PL/SQL Constant A constant holds a value that once declared, does not change in the program. A constant declaration specifies its name, data type, and value, and allocates storage for it. The declaration can also impose the NOT NULL constraint. A constant can be declared using the CONSTANT keyword. Example pi constant double precision := 3.1415;

PL/SQL PL/SQL Literals PL/SQL, literals are case-sensitive. PL/SQL supports the following kinds of literals Literal Examples Numeric Literals 10,2,-34,45.8 Character Literals 'A' '%' '9' ' ' 'z' String Literals 'Hello, world!' 'popo' BOOLEAN Literals TRUE, FALSE, and NULL. Date and Time Literals DATE '1978-12-25'; TIMESTAMP '2012-10-29 12:01:01';

PL/SQL PL/SQL Literals To embed single quotes within a string literal, place two single quotes next to each other Example message varchar2(20):= ''ajith'' s site poposir.orgfree.com'; Will print ajith’s site poposir.orgfree.com

PL/SQL PL/SQL Operators Operators are symbols to perform some operation They are Arithmetic operators +, -, *, /, ** (power eg 2**3 8) Relational operators =, <, >, <=, >=, <> or != or ~= Logical operators and, or, not Comparison operators LIKE, BETWEEN, IN, IS NULL

PL/SQL Arithmetic operators Example BEGIN dbms_output.put_line( 10 + 5); dbms_output.put_line( 10 - 5); dbms_output.put_line( 10 * 5); dbms_output.put_line( 10 / 5); dbms_output.put_line( 2 ** 3); END; / Output 15 5 50 2 8

PL/SQL Relational operators example declare a number(2); b number(2); Begin a:=&a; b:=&b; if(a>b) then dbms_output.put_line('a is big'); else dbms_output.put_line('b is big'); end if; end; / Output A is big

PL/SQL Logical operator example declare a int:=10; b int:=20; begin if(a=10 and b=20) then dbms_output.put_line('happy'); else dbms_output.put_line('sorry'); end if; end; Output happy

PL/SQL Comparison operator between example declare a number; begin a:=&a; if(a between 5 and 20) then dbms_output.put_line('yes'); else dbms_output.put_line('no'); end if; end; Output yes

PL/SQL Comparison operator like example declare a varchar(20):='popo'; begin if(a like 'p%o') then dbms_output.put_line('found'); else dbms_output.put_line('not found'); end if; end; Output found

PL/SQL Comparison operator In and IS NULL example declare a varchar(1):='a'; begin if(a in ('a', 'p', 's')) then dbms_output.put_line('found'); else dbms_output.put_line('not found'); end if; if(a is null) then dbms_output.put_line(a||' is null'); dbms_output.put_line(a||' not null'); end; Output found a not null

PL/SQL Decision Making Statements If - then statement If – then – else statement If – then – elsif statement Case statement

PL/SQL Decision Making Statements If - then statement Syntax IF condition THEN statements; END IF; example

PL/SQL Decision Making Statements If – then - else statement Syntax IF condition THEN true block statements; ELSE false block statements; END IF; example

PL/SQL Decision Making Statements If – then – elsif statement Syntax IF condition-1 THEN true block statements1; ELSIF condition-2 THEN true block statements2; ELSIF condition-3 THEN true block statements3; ELSE false block statements; END IF; example

PL/SQL Decision Making Statements Case statement Syntax CASE selector WHEN 'value1' THEN Sts1; WHEN 'value2' THEN Sts2; WHEN 'value3' THEN Sts3; ... ELSE Sn; -- default case END CASE;

PL/SQL Decision Making Statements Example Case statement DECLARE grade char(1) := 'A'; BEGIN CASE grade when 'A' then dbms_output.put_line('Excellent'); when 'B' then dbms_output.put_line('Very good'); when 'C' then dbms_output.put_line('Well done'); when 'D' then dbms_output.put_line('You passed'); when 'F' then dbms_output.put_line('Better try again'); else dbms_output.put_line('No such grade'); END CASE; END; example

PL/SQL Loops Basic loop While loop For loop Nested loop

PL/SQL Loops Example Output 1,……,10 Basic loop synatx LOOP Sequence of statements; END LOOP; Example declare a int:=1; b int:=10; begin loop dbms_output.put_line(a); a:=a+1; if(a>b) then exit; /*break a loop*/ end if; end loop; end; Output 1,……,10

PL/SQL Loops Example declare a int:=1; b int:=10; begin while loop synatx WHILE condition LOOP sequence_of_statements END LOOP; Example declare a int:=1; b int:=10; begin while a<=b loop dbms_output.put_line(a); a:=a+1; end loop; end; Output 1,2, , , 10

PL/SQL floor()  returns integer value Reverse given no declare n int; b int; r int:=0; begin n:=&n; while n >0 loop b:= n mod 10; r:= r*10+b; n:=floor(n/10); end loop; dbms_output.put_line(r); end; Output Enter value of n 1234 4321 floor()  returns integer value

PL/SQL Loops for loop Synatx FOR counter IN initial_value .. final_value LOOP sequence_of_statements; END LOOP;

PL/SQL Loops Even nos up to the limit for loop Example declare a int; Begin for a in 1 .. 10 loop dbms_output.put_line(a); end loop; end; Output 1,2, , , 10 Even nos up to the limit declare n int; i int; begin n:=&n; for i in 1 .. n loop if i mod 2 = 0 then dbms_output.put_line(i); end if; end loop; end; / Output Enter value of n 10 2 4 , , 10

PL/SQL Output 1 12 123 1234 12345 123456 1234567 Loops Nested loop Example declare i int; j int; begin for i in 1 .. 7 loop for j in 1 .. i loop dbms_output.put(j); end loop; dbms_output.put_line(' '); End; Output 1 12 123 1234 12345 123456 1234567

PL/SQL String functions CONCAT(x, y); Concatenates the strings x and y and return the appended string. INITCAP(x); Converts the initial letter of each word in x to uppercase and returns that string. LENGTH(x); Returns the number of characters in x. LOWER(x); Converts the letters in x to lowercase and returns that string. REPLACE(x, search_string, replace_string); Searches x for search_string and replaces it with replace_string. UPPER(x); Converts the letters in x to uppercase and returns that string.

PL/SQL String function concat() example declare s1 varchar(4):='popo'; s2 varchar(3):='sir'; begin dbms_output.put_line(concat(s1,s2)); end; Output poposir

PL/SQL String function trim() example DECLARE greetings varchar2(30) := '...popo...'; BEGIN dbms_output.put_line(RTRIM(greetings,'.')); dbms_output.put_line(LTRIM(greetings, '.')); dbms_output.put_line(TRIM( '.' from greetings)); END; Output …popo Popo… popo

PL/SQL Array PL/SQL programming language provides a data structure called the VARRAY which can store a fixed-size sequential collection of elements of the same type. A varray is used to store an ordered collection of data. Varrays consist of contiguous memory locations. Each element in a varray has an index associated with it.

PL/SQL Array A varray type Syntax type varray_type_name IS VARRAY(n) of <element_type> Example type name IS VARRAY(5) OF VARCHAR2(10); type grade IS VARRAY(5) OF INTEGER;

PL/SQL Procedures Array declare type nos is varray(5) of int; m nos; i int; begin m:=nos(1,2,3,4,5); for i in 1 .. m.count loop dbms_output.put_line(m(i)); end loop; end; /

PL/SQL Array declare type array is varray(3) of varchar2(10); a array := array('popo', 'peepe', 'raji'); i int; begin for i in 1..a.count loop dbms_output.put_line(a(i)); end loop; end; /

PL/SQL DECLARE CURSOR c_tab1 is SELECT name FROM tab1; Array ( to read column value to an array) Table tab1(rollno,name) DECLARE CURSOR c_tab1 is SELECT name FROM tab1; type list is varray (2) of tab1.name%type; name_list list := list(); counter integer :=0; n int; BEGIN FOR n IN c_tab1 LOOP counter := counter + 1; name_list.extend; name_list(counter) := n.name; dbms_output.put_line('Sudent ('||counter ||') : '||name_list(counter)); END LOOP; END; Output Student (1) : aji Student (2) : saji rollno name 1 aji 2 saji