Download presentation
Presentation is loading. Please wait.
1
PL/SQL (1)
2
Learning Objectives In this chapter, you will learn:
About procedural SQL About PL/SQL structure How to declare variables in PL/SQL About data types in PL/SQL About conditional and iterative structure in PL/SQL About cursors, how to create and use them
3
Introduction Performs a conditional or looping operation by isolating critical code and making all application programs call the shared code Yields better maintenance and logic control Persistent stored module (PSM): Block of code containing: Standard SQL statements Procedural extensions that is stored and executed at the DBMS server To remedy the lack of procedural functionality in SQL and to provide some standardization within the many vendor offerings, the SQL-99 standard defined the use of persistent stored modules.
4
What is PL/SQL Procedural Language SQL (PL/SQL)
An Oracle-specific programming language based on SQL with procedural extensions designed to run inside the Oracle database. Use and storage of procedural code and SQL statements within the database Merging of SQL and traditional programming constructs Procedural code is executed as a unit by DBMS when invoked by end user
5
PL/SQL Structure PL/SQL is an algorithmic, block-structured language.
PL/SQL groups its statements into units called BLOCKS which can be unnamed (anonymous) or named ( sub- programs) PL/SQL blocks can contain only SQL DML commands ( SELECT, INSERT, UPDATE, and DELETE) and Transaction Commands which are COMMIT & ROLLBACK. The use of data definition language (DDL) commands (Create, Alter, Drop, etc.) is not directly supported in a PL/SQL block.
6
PL/SQL Structure The subprograms can be either – Functions, procedures, and they can be grouped into a packages. PL/SQL also allows access to databases via Cursors, Triggers, stored procedures and functions.
7
PL/SQL Structure A block has three parts: Declaration, Executable and Exception-handling. A block has the following structure. DECLARE Declarations -- Optional BEGIN Executable -- Mandatory EXCEPTION Exception-handling /* here you can specify the actions to execute when the program encounters a runtime error; it is optional */ END; The three parts of a block are separated by the DECLARE, BEGIN, EXCEPTION, and END PL/SQL reserved words. You should not use any reserved word for any other than its designated purpose.
8
Declaration Part Variables used to hold program data are declared in the Declaration part. All declaration statements must be located between the DECLARATION and BEGIN reserved words. The syntax of a variable declaration is: identifier data_type; The Declaration part is optional, but any variable used in Executable part must be declared; otherwise, the program will fail. In addition to variable, you can also declare other program objects, such as Constant and Exception A variable name must start with a letter; the rest can be letters, digits, or any of the following three symbols: _ (underscore), # (number sign), and $ (dollar sign). The maximum length of a name is 30 characters. Additionally, PL/SQL is not case sensitive. The following four variable names, for example, are not valid. 9code_var -- start with numeric Name_var% -- has a % character price var -- has a blank Date_the_price_of_this_produce_was_changed_var -- longer than 30 characters
9
Data types and variables
all the sql data types variables declaration: <variable-name> <datatype> [not null] [:=<initial value>] ex. sid number(5) not null := 1111; sname varchar2(30); grade number(5,2) := 2.5; constants declaration: <constant-name> constant <data-type> := <value> ex. maxcolumns constant integer(2) := 30;
10
Table 8.9 - PL/SQL Basic Data Types
11
Anchor Variables: ROWTYPE and TYPE
The syntax of the ROWTYPE and TYPE datatypes syntaxes are respectively: variable_name table_name%ROWTYPE; variable_name table_name.column_name%TYPE; You use ROWTYPE at once refer to all the columns of a table; while the TYPE refers to a specific column. ex. cnum customers.sid%type; ctable customers%rowtype; -- creates a variable of type table that has the same fields as the customers table;
12
Storing Data in Variables (SELECT INTO)
The SELECT INTO clause of SQL is used to retrieve data from one or more database tables and place the returned data into predefined variables.
13
IF…THEN…ELSIF … ELSE … END IF
Control Structures Control Structures Conditional Statements Iterative Statements IF….. THEN…..END IF LOOP … END LOOP IF…THEN…ELSE… END IF WHILE … LOOP …. END LOOP IF…THEN…ELSIF … ELSE … END IF FOR … LOOP … END LOOP
14
Conditional Statements
Actions are triggered based on the result of conditions
15
Conditional statements
The syntax of the Simple CASE statement is. Note: Selector should be of simple type CASE selector WHEN selector_value_1 THEN statements_1 WHEN selector_value_2 THEN statements_2 WHEN ... [ ELSE else_statements ] END CASE;
16
Iterative statements Loops repeat an instruction or a set of instructions multiple times. Three types of loops: basic loop, For Loop and While Loop. The EXIT instruction exits the loop Basic Loop LOOP Start of the Loop instruction1 ; Instructions . . . EXIT [ WHEN condition ]; -- Exit the Loop END LOOP ; End of the Loop
17
Basic Loop - Example The following PL / SQL program displays multiples of 3, 4 and 5 which are between 4 and 32 DECLARE i NUMBER(2) := 4; BEGIN LOOP IF (MOD(i,3)=0) THEN DBMS_OUTPUT.PUT_LINE (i || ‘ is a multiple of 3’); END IF; IF (MOD(i,4)=0) THEN DBMS_OUTPUT.PUT_LINE (i || ‘ is a multiple of 4’); IF (MOD(i,5)=0) THEN DBMS_OUTPUT.PUT_LINE (i || ‘ is a multiple of 5’); i := i+1; EXIT WHEN i>32; END LOOP; END;
18
FOR Loop - Example The following PL / SQL program calculates the factorial of 10 using For Loop. DECLARE fact_num NUMBER := 1; BEGIN FOR v_counter IN LOOP fact_num := fact_num * v_counter; END LOOP; DBMS_OUTPUT.PUT_LINE('Factorial of 10 is: '||fact_num); END;
19
While Loop - Example The following PL / SQL program calculates the factorial of 10 using While Loop. DECLARE n_counter NUMBER := 10; n_factorial NUMBER := 1; n_temp NUMBER; BEGIN n_temp := n_counter; WHILE n_counter > 0 LOOP n_factorial := n_factorial * n_counter; n_counter := n_counter - 1; END LOOP; DBMS_OUTPUT.PUT_LINE('factorial of ' || n_temp || ' is ' || n_factorial); END;
20
FOR LOOP WITH INSERT- Example
CREATE TABLE item(ItemNum NUMBER(2)); BEGIN FOR num IN 1..5 LOOP INSERT INTO item VALUES(num); END LOOP; END; / SELECT * FROM item;
21
PL/SQL Processing with Cursors
Oracle server uses work areas called Private SQL Zones to execute SQL statements and to store information being processed You can use PL / SQL cursors to name a private SQL area and access the data it contains. A memory area of fixed size containing the result of a query. Used to interpret and analyze SQL statements. Cursors You can think of a cursor as a reserved area of memory in which the output of the query is stored, like an array holding columns and rows. Cursors are held in a reserved memory area in the DBMS server, not in the client computer. Implicit: generated and managed by ORACLE for each SQL statement Explicit: Declared by developers in the DECLARE section of a PL/SQL block
22
Explicit Cursors The use of an explicit cursor requires fours steps:
Declaration of the cursor in declare section Opening the cursor in Begin section Processing the cursor in Begin section Closing the cursor in Begin or Exception section
23
Declaration of a cursor
Cursor’s declaration Syntax: Declare Cursor <cusor_name> IS SELECT col1, col2, col3, …. FROM tab1, tab2, tab3, … Where <Condition>; …. Declaration of a cursor Example: Declare Cursor c_employee IS SELECT empNo, empName, salary FROM employee Where salary between 1000 AND 2500;
24
OPEN <cursor_name> ;
Cursor’s Opening Opening the cursor realizes: Allocation of the memory to the cursor semantic and syntactic analysis of the SQL statement It is only when the cursor is opened that the SQL query is executed The cursor is opened in the Begin section of the block as follows: OPEN <cursor_name> ;
25
Cursors’ processing Cursor-style processing involves retrieving data from the cursor one row at a time Current row is copied to PL/SQL variables After the fetch, the “current” row pointer moves to the next row in the set and continues until it reaches the end of the cursor.
26
Table 8.10 - Cursor Processing Commands
27
Table 8.11 - Cursor Attributes
28
Cursor - Example END; END; CURSOR with FOR LOOP CURSOR with LOOP
DECLARE Cursor c_customers is Select id, name, address From customers; cusRecord c_customers%rowtype; BEGIN For cusRecord in c_customers Loop dbms_output.put_line (cusRecord .id||’’|| cusRecord .name||’’|| cusRecord.address); END LOOP; END; DECLARE c_id customers.id%type; c_name customers.name%type; c_addr customers.address%type; Cursor c_customers is Select id, name, address From customers; BEGIN Open c_customers; LOOP Fetch c_customers into c_id, c_name, c_addr; EXIT When c_customers%notfound; dbms_output.put_line (c_id||’’||c_name||’’||c_addr); END LOOP; Close c_customers; END;
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.