Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć2Schedule: Timing Topic 40 minutes Lecture 45 minutes Practice 85 minutes Total Class Management Note: Files required fo
Trang 1Interacting with Oracle
22
Trang 2Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć2
Schedule: Timing Topic
40 minutes Lecture
45 minutes Practice
85 minutes Total
Class Management Note:
Files required for lesson
Demonstration: l22cust.pls, l22newsd.pls, l22delr.pls
Practice: None
Trang 3Interacting with Oracle 22Ć3
In this lesson, you access the database and control transactions through SQL statements in PL/SQL.
At the end of this lesson, you should be able to
D Use SELECT, INSERT, UPDATE, and DELETE commands in PL/SQL
subprograms
D Determine the outcome of SQL statements by using implicit cursor attributes
D Control transactions within PL/SQL
Trang 4Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć4
Class Management Note:
Remind students that they will combine the commands covered in thislesson with the subprograms learned in the previous lessons
Trang 5Interacting with Oracle 22Ć5
When you need to extract information from or apply changes to the database, youmust use SQL PL/SQL supports full data manipulation language and transactioncontrol commands within SQL You can use SELECT statements to populate
variables with values queried from a row in a table Your DML commands canprocess multiple rows
Comparing SQL and PL/SQL Statement Types
D A PL/SQL block is not a transaction unit Commits, savepoints, and rollbacks areindependent of blocks, but you can issue these commands within a block
D PL/SQL does not support data definition language (DDL), such as CREATETABLE, ALTER TABLE, or DROP TABLE
D PL/SQL does not support data control language (DCL), such as GRANT orREVOKE
D DBMS_SQL package allows you to issue DDL and DCL statements
Class Management Note:
DBMS_SQL package is a new package available in Oracle7 Release 7.2
For more information about DBMS_SQL package, see Oracle7 Server
Application Developer’s Guide, Release 7.2.
Trang 6Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć6
Class Management Note:
The INTO clause is required in a SELECT statement in PL/SQL This is incontrast to SQL, where the INTO clause is forbidden
Output variables are PL/SQL variables through which values pass from thedatabase out to the PL/SQL block The datatype of an output variable must
be compatible with the datatype of the source column, although the sourcecolumn may be an expression; in particular, Boolean variables are notpermitted
Input variables are PL/SQL variables through which values pass from thePL/SQL block into the database
Trang 7Interacting with Oracle 22Ć7
Use the SELECT statement to retrieve data from the database The SELECT
statement contains an additional mandatory clause: the INTO clause In the INTOclause, list the output variables for receiving the data The SELECT statement mustreturn exactly one row or an error will occur
where: select_list is a list of at least one column, and can include
SQL expressions, row functions, or groupfunctions
variable_name is the scalar variable to hold the retrieved value
record_name is the PL/SQL RECORD to hold the retrieved
values
table specifies the database table name
condition is composed of column names, expressions,
constants, and comparison operators, includingPL/SQL variables and constants
Take advantage of the full range of Oracle7 Server syntax for the SELECT statement.Guidelines
D Terminate each SQL statement with a semicolon (;)
D Assign values into PL/SQL tables in a loop by declaring an explicit cursor
D The INTO clause is required for the SELECT statement when it is embedded
within PL/SQL
D The WHERE clause is optional, and can be used to specify input variables,constants, literals, or PL/SQL expressions
Trang 8Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć8
Trang 9Interacting with Oracle 22Ć9
Guidelines
D Specify the same number of output variables in the INTO clause as databasecolumns in the SELECT clause Be sure that they correspond positionally and thattheir datatypes are compatible
D Ensure that the datatype of the identifiers match the datatype of the columns byusing the %TYPE attribute The datatype and number of variables in the INTOclause match those in the SELECT list
D Terminate the PL/SQL block with the END statement You can add the name ofthe subprogram after the keyword END for clarity
D Include at least one RETURN statement in a function
D Use group functions, such as SUM, in a SQL statement since group functionsapply to groups of rows in a table
Class Management Note:
On the board, write: v_sum_salaries := SUM (s_emp.salary),and draw a line through it to emphasize that group functions must be used
in a SQL statement
Trang 10Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć10
Class Management Note:
Question: Ask students what the record structure looks like
Answer: Three fields, ID, NAME, and REGION_ID
Question: Ask students how to reference the value in the NAME field of therecord
Answer: Reference the value as DEPT_RECORD.NAME
Trang 11Interacting with Oracle 22Ć11
A PL/SQL RECORD can be used to easily create fields that match a database table’scolumns Each field has the same name and datatype as a column in the table Whenretrieving all columns from a table, use a PL/SQL RECORD to hold the retrievedvalues
Class Management Note:
Note for page 22-16
Question: Ask students how to change the code to avoid receiving the error
Answer: Name the identifiers with the v_ prefix.
Trang 12Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć12
Trang 13Interacting with Oracle 22Ć13
Avoid ambiguity in the WHERE clause by adhering to a naming convention thatdistinguishes database column names from PL/SQL variable names
Example
Retrieve the order date and the ship date for the specified order This example raises
an unhandled runtime exception.
SELECT date_ordered, date_shipped
INTO date_ordered, date_shipped
ERROR 0 at line 1, column 0
Unhandled exception ORA-01422: exact fetch returns
more than requested number of rows
Trang 14Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć14
Class Management Note:
Exceptions are covered in a later lesson
Trang 15Interacting with Oracle 22Ć15
SELECT statements within a PL/SQL block fall into the “Embedded SQL”ANSI
classification Be sure that the SELECT statement retrieves exactly one row;
otherwise an exception is raised An exception is an error that terminates a PL/SQLblock
SELECT Exceptions
The SELECT statement identifies more
than one row
TOO_MANY_ROWS exception(Oracle7 Server error number -1422).The SELECT statement does not identify
any rows
NO_DATA_FOUND exception (Oracle7Server error number +1403)
Note: Handle the raised exceptions with exception-handling routines, which will be
covered in a later lesson Alternatively, fetch multiple rows one-by-one in aloop by declaring an explicit cursor
Trang 16Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć16
Trang 17Interacting with Oracle 22Ć17
TOO_MANY_ROWS Exception
When more than one record is identified with a SELECT statement, Oracle7 Serverraises an error number -1422, also referred to as TOO_MANY_ROWS, which is thepredefined exception name
Trang 18Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć18
Trang 19Interacting with Oracle 22Ć19
Manipulate data in the database by using the DML commands
D INSERT statement adds new rows of data to the table
D UPDATE statement modifies existing rows in the table
D DELETE statement removes unwanted rows from the table
Inserting Data
When adding rows to a table, you can eliminate unnecessary IN arguments
D Use SQL function, such as USER and SYSDATE
D Generate primary key values by using database sequences
D Derive values in the PL/SQL block
D Add column default values
Technical Note:
There is no possibility for ambiguity with identifiers and column names inthe INSERT statement Any identifier in the INSERT clause must be adatabase column name
Class Management Note:
DEMO: l22cust.pls
PURPOSE: This example demonstrates using the INSERT commandsembedded in a procedure
1 Select from the menu File—>Load, and load the l22cust.pls file.
2 Show the code to the students
3 Execute the procedure at the Interpreter prompt
Enter: cust_order(201);
4 Verify the change to the table Enter: SELECT * FROM s_ord
WHERE customer_id = 201;
Trang 20Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć20
Trang 21Interacting with Oracle 22Ć21
Updating and Deleting Data
There may be ambiguity in the SET clause of the UPDATE statement because
although the identifier on the left of the assignment operator is always a databasecolumn, the identifier on the right can be either a database column or a PL/SQLvariable
Remember that the WHERE clause is used to determine which rows are affected If
no rows are modified, no error occurs, unlike the SELECT statement in PL/SQL
Technical Note:
PL/SQL variable assignments always use “:=”; SQL column assignmentsalways use “=”
Recall that if column names and identifier names are identical in the
WHERE clause, the Oracle7 Server looks to the database first for the name
Class Management Note:
DEMO: l22newsd.pls
PURPOSE: Show the use of parameters in a procedure to update a value inthe table
1 Select from the menu File—>Load, and load the l22newsd.pls file.
2 Show the code to the students
3 Execute the procedure at the Interpreter prompt
Enter: new_ship_date(101,’7-Nov-95’);
4 Verify the change to the table
Enter: SELECT * FROM s_ord WHERE id = 101;
Trang 22Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć22
Trang 23Interacting with Oracle 22Ć23
Whenever you issue a SQL command, the Server opens an area of memory in which
the command is parsed and executed This area is called a cursor.
When the executable part of a block issues a SQL command, PL/SQL creates animplicit cursor, which has the SQL identifier PL/SQL manages this cursor
automatically An explicit cursor is explicitly declared and named by the programmer.There are four attributes available in PL/SQL that can be applied to cursors
Note: More about explicit cursors will be covered in Lesson 24.
SQL Cursor Attributes
You can use these attributes in PL/SQL statements as you would functions, but not inSQL commands They are useful to evaluate the result of a DML operation PL/SQLdoes not consider a data manipulation language statement that affects no rows to havefailed, unlike the SELECT statement, which returns an exception
Attribute Description
SQL%ROWCOUNT Number of rows affected by the most recent SQL
statement (an integer value)
SQL%FOUND Boolean attribute that evaluates to TRUE if the most
recent SQL statement affects one or more rows.SQL%NOTFOUND Boolean attribute that evaluates to TRUE if the most
recent SQL statement does not affect any rows.SQL%ISOPEN Always evaluates to FALSE because PL/SQL closes
implicit cursors immediately after they are executed
For more information, see
PL/SQL User’s Guide and Reference, Release 2.3, Chapter 4, “Implicit Cursor
Attributes” section
Class Management Note:
You can also use the attributes in the EXCEPTION section of a block toevaluate the results of a failed SELECT statement This topic will be
covered in a later lesson
Trang 24Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć24
Class Management Note:
DEMO: l22delr.pls
PURPOSE: Show students that the SQL cursor attributes indicate thenumber of rows affected Show that if no rows are deleted, there is no error,unlike with the SELECT statement, which produces an exception
Procedure Builder instructions:
1 Select from the menu File—>Load, and load the l22delr.pls file.
2 Show the code to the students
3 Execute the procedure at the Interpreter prompt
Enter: del_rows(100);
4 Roll back the changes when done
Trang 25Interacting with Oracle 22Ć25
DELETE FROM s_item
WHERE ord_id = v_ord_id;
1 Show the code in the l22delrs.sql file.
2 Start the file to create the procedure
3 Create the global variable to print out the result
Enter: variable g_rows_deleted VARCHAR2(25)
4 Execute the procedure at the prompt
Enter: execute del_rows(100, :g_rows_deleted);
5 Print the results Enter: print g_rows_deleted
6 Roll back the changes when done
Trang 26Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć26
Trang 27Interacting with Oracle 22Ć27
Control the logic of transactions with COMMIT and ROLLBACK SQL commands,rendering some groups of database changes permanent, while discarding others Aswith Oracle7, DML transactions start at the first command to follow a COMMIT orROLLBACK, and end on the next successful COMMIT or ROLLBACK Theseactions may occur within a PL/SQL block or as a result of events in the host
environment (for example, ending a Procedure Builder session automatically commitsthe pending transaction)
You can also include explicit locking commands (such as LOCK TABLE and
SELECT FOR UPDATE) in a block They take effect until the end of the
where: WORK is for compliance with ANSI standards
Note: A transaction is defined as a sequence of SQL statements.
Trang 28Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć28
Trang 29Interacting with Oracle 22Ć29
SAVEPOINT Command
Alter the transactional logic with Oracle7 Server savepoints based upon runtimeconditions SAVEPOINT marks an intermediate point in the transaction processing.Syntax
SAVEPOINT savepoint_name;
ROLLBACK TO SAVEPOINT discards pending changes made after the savepointwas marked
Syntax
ROLLBACK [WORK] TO [SAVEPOINT] savepoint_name;
where: savepoint_name is a PL/SQL identifier
Technical Note:
SAVEPOINT is not ANSI standard It is an Oracle extension of the standardSQL language You can have more than one savepoint per transaction, eachidentified by a different marker name If you create a second savepoint withthe same marker name, the previous savepoint is erased Savepoints areespecially useful with conditional logic
Class Management Note:
Question: How many rows are inserted?
Trang 30Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć30
Trang 31Interacting with Oracle 22Ć31
You can embed SQL within the PL/SQL block You can use the following validcommands:
Statement Description
SELECT Retrieves exactly one row into scalar variables or into a
record variable
UPDATE Modifies one or more existing rows
DELETE Removes one or more existing rows
COMMIT Makes all pending transactions permanent
ROLLBACK Eliminates all pending transactions
Trang 32Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć32
Trang 33Interacting with Oracle 22Ć33
In this practice, you create three procedures to input, update, and delete information
in a table, all using DML statements within a PL/SQL block
Practice Contents
D Creating a procedure to insert data into a table
D Creating a procedure to update data in a table
D Creating a procedure to delete a record from a table
D Verifying your changes to the table using Oracle Procedure Builder built-ins andimplicit cursor attributes
Class Management Note:
Duration: 45 minutes
For additional exercises, see Practice 26, Exercises 1a and 1d
Trang 34Introduction to Oracle: SQL and PL/SQL Using Procedure Builder 22Ć34
Trang 35Interacting with Oracle 22Ć35
If you are not already connected to the database, be sure to connect now
1. Create a procedure to insert a new department into the S_DEPT table
a. Use the S_DEPT_ID sequence generator for the department number
b. Create a parameter for the department name
c. Leave the region number null for now
d. Execute the procedure
e. Display the new department that you created
2. Create a procedure to update the region number for an existing department
a. Create a parameter for the department number
b. Create a parameter for the region name
c. Set the region number to the value that corresponds to the specified regionname
d. Test the procedure What happens if you enter a region name that does notexist?
e. Display the department number, region number, and region name for theupdated department
3. Create a procedure to delete the department created in Exercise 1
a. Create a parameter for the department number
b. Print to the screen the number of rows affected
c. Test the procedure What happens if you enter a department number that doesnot exist?
What happens if you enter a department that has employees?
d. Confirm that the department has been deleted