Download presentation
Presentation is loading. Please wait.
Published byHendra Tedjo Modified over 6 years ago
1
Chapter 2 Handling Data in PL/SQL Blocks Oracle9i Developer:
PL/SQL Programming Chapter 2 Handling Data in PL/SQL Blocks
2
Chapter Objectives Learn about the PL/SQL block Define variables
Create scalar variables Include SQL within PL/SQL Execute a PL/SQL block Use host or bind variables
3
Chapter Objectives Understand the %TYPE attribute
Use composite data types Process conditional logic with IF statements and loops Create collections Manipulate data with cursors Identify variable scope
4
PL/SQL Block Questions
What is a block? What are the different segments of a block? How does data get into a block? How are different data types handled?
5
Brewbean’s Challenge
6
PL/SQL Block Structure
DECLARE – create variables, cursors, and types BEGIN – SQL, logic, loops, assignment statements EXCEPTION – error handling END – close the block
7
Variable Names Begin with alpha character Up to 30 characters
Can contain upper and lower-case letters, numbers, _ , $ , #
8
Scalar Variable Data Types
Character – CHAR(n) and VARCHAR2(n) Numeric – NUMBER(p,s) Date – DATE Boolean – BOOLEAN Note: Only holds a single value
9
Example Scalar Declarations
DECLARE lv_ord_date DATE; lv_last_txt VARCHAR2(25); lv_qty_num NUMBER(2); lv_shipflag_bln BOOLEAN; BEGIN ---- PL/SQL executable statements ---- END; Note: Minimum requirements are variable name and data type
10
Variable Initialization
DECLARE lv_ord_date DATE := SYSDATE; lv_last_txt VARCHAR2(25) := 'Unknown'; lv_qty_num NUMBER(2) := 0; lv_shipflag_bln BOOLEAN := 'FALSE'; BEGIN ---- PL/SQL executable statements ---- END;
11
Variable Declaration Options
DECLARE lv_shipcntry_txt VARCHAR2(15) NOT NULL := 'US'; lv_taxrate_num CONSTANT NUMBER(2,2) := .06; BEGIN ---- PL/SQL executable statements ---- END;
12
Display Variable Values
13
Include SQL within a Block
Data query needs
14
Include SQL within a Block
Query Assignment Statement
15
Executing a Block with Errors
Common Errors Use = rather than := Not declaring a variable Misspelling a variable name Not ending a statement with ; No data returned from a SELECT statement
16
Executing a Block with Errors
Not closing a statement with ;
17
Host or Bind Variables Represent values that exist in the application environment Typically these values reference objects on user application screens Create SQL*Plus variables with the VARIABLE command Reference host variables with a preceding colon in PL/SQL
18
%TYPE Attribute Use in variable declaration to provide data type based on a table column Ideal for declaring variables that will hold data from the database Minimizes maintenance by avoiding program changes to reflect database column changes Called an anchored data type lv_basket_num bb_basket.idBasket%TYPE;
19
Composite Data Types Stores multiple values of different data types as one unit Record – can hold one row of data Table of records – can hold multiple rows of data
20
Record Data Type DECLARE TYPE type_basket IS RECORD (
basket bb_basket.idBasket%TYPE, created bb_basket.dtcreated%TYPE, qty bb_basket.quantity%TYPE, sub bb_basket.subtotal%TYPE); rec_basket type_basket; lv_days_num NUMBER(3); lv_shopper_num NUMBER(3) := 25; BEGIN SELECT idBasket, dtcreated, quantity, subtotal INTO rec_basket FROM bb_basket WHERE idShopper = lv_shopper_num AND orderplaced = 0; lv_days_num := SYSDATE - rec_basket.created; END;
21
%ROWTYPE Attribute DECLARE rec_shopper bb_shopper%ROWTYPE; BEGIN
SELECT * INTO rec_shopper FROM bb_shopper WHERE idshopper = :g_shopper; DBMS_OUTPUT.PUT_LINE(rec_shopper.lastname); DBMS_OUTPUT.PUT_LINE(rec_shopper.address); DBMS_OUTPUT.PUT_LINE(rec_shopper. ); END;
22
Table of Records
23
IF Statement Provides a mechanism to check a condition Example:
IF SYSDATE-lv_created > 7 THEN lv_flag := ‘Expired’; END IF;
24
Basic Loop Loops enable the repeating of statements Example: LOOP
lv_bonus_num := lv_sales_num * lv_rate_num; lv_total_num := lv_total_num + lv_bonus_num; EXIT WHEN lv_total_num > 8000; END LOOP;
25
For Loop FOR i IN 1..lv_cnt LOOP INSERT INTO bb_basketitem
(idBasketitem,idProduct,idBasket, price, quantity) VALUES (bi_seq,NEXTVAL, tbl_cart(i).prod,tbl_cart(i).bask, tbl_cart(i).price,tbl_cart(i).qty); END LOOP;
26
Collections Store multiple values of the same data type
Similar to arrays in other languages Index-by Tables – handle many rows of one field One-dimensional Can only have one column. Unconstrained Rows added dynamically as needed. Sparse A row only exists when a value is assigned. Rows do not have to be assigned sequentially. Homogeneous All elements have same data type. Indexed Integer index serves as primary key of the table.
27
Index-by Table Attributes
Attribute Name Value Data type Description COUNT NUMBER Number of rows in the table DELETE None Removes a row from the table EXISTS BOOLEAN TRUE if specified row does exist FIRST BINARY_INTEGER Index for the first row in the table LAST Index for the last row in the table NEXT Index for the next row in the table after the row specified PRIOR Index for the row in the table before the row specified
28
Index-by Table Example
Host variables declaration and initialization
29
Index-by Table Example
Index-by table data type declaration Index-by table variable declaration Put host variable values into the table variable A for loop adds all the sample measurements that have been entered into the table variable lv_avg_num calculates the Average measurement
30
Cursors Work area in which SQL statement is processed
Implicit cursor – declared automatically for DML and SELECT statements Explicit cursor – declared and managed programmatically to handle a set of rows returned by a SELECT statement Cursor variable – reference or pointer to a work area or cursor
31
Cursor Attributes Attribute Name Data type Description %ROWCOUNT
Number Number of rows affected by the SQL statement %FOUND Boolean TRUE if at least one row is affected by the SQL statement, otherwise FALSE %NOTFOUND TRUE if no rows are affected by the SQL statement, otherwise FALSE
32
Implicit Cursor
33
Explicit Cursor Step Step Activity Activity Description 1 DECLARE
Creates a named cursor identified by a SELECT statement. The SELECT statement does not include an INTO clause. Values in the cursor are moved to PL/SQL variables with the FETCH step. 2 OPEN Processes the query and creates the active set of rows available in the cursor. 3 FETCH Retrieves a row from the cursor into block variables. Each consecutive FETCH issued will retrieve the next row in the cursor until all rows have been retrieved. 4 CLOSE Clears the active set of rows and frees the memory area used for the cursor.
34
Explicit Cursor Example
Declare cursor Declare record type and variable Open cursor Fetch a row from the cursor Check if row returned from fetch Close cursor Calculate tax amount
35
Cursor FOR Loop Handles tasks automatically for processing each row returned by a cursor (record declaration, fetch, ending loop) Use FOR UPDATE and WHERE CURRENT OF clauses for record locking
36
Cursor FOR Loop Example
DECLARE CURSOR cur_prod IS SELECT type, price FROM bb_product WHERE active = 1 FOR UPDATE NOWAIT; lv_sale bb_product.saleprice%TYPE; BEGIN FOR rec_prod IN cur_prod LOOP IF rec_prod.type = 'C' THEN lv_sale := rec_prod.price * .9; END IF; IF rec_prod.type = 'E' THEN lv_sale := rec_prod.price * .95; UPDATE bb_product SET saleprice = lv_sale WHERE CURRENT OF cur_prod; END LOOP; COMMIT; END;
37
Cursor Variable More efficiently handles data returned by query by returning a pointer to the work area rather than the actual result set The same cursor variable can be used for different query statements
38
Cursor Variable Example
DECLARE TYPE type_curvar IS REF CURSOR; cv_prod type_curvar; rec_coff bb_coffee%ROWTYPE; rec_equip bb_equip%ROWTYPE; BEGIN IF :g_choice = 1 THEN OPEN cv_prod FOR SELECT * FROM bb_coffee; FETCH cv_prod INTO rec_coff; . . . END IF; IF :g_choice = 2 THEN OPEN cv_prod FOR SELECT * FROM bb_equip; FETCH cv_prod INTO rec_equip; END;
39
Variable Scope When nesting PL/SQL blocks, variable scope refers to the blocks that can identify a particular variable Inner blocks can reference variables in outer blocks Outer blocks can NOT reference variables in inner blocks
40
Summary Variables hold data values
Variable types: scalar, composite, collections SQL statements can be embedded in a PL/SQL block A SELECT statement must include an INTO clause Cursors are work areas to handle the results data set of a query
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.