23.3 Grouping Privileges Using Roles 523Chapter 23 Note: PL/SQL code blocks may not recognize database access through roles.. A role that will contain sensitive privileges can be assigne
Trang 1520 23.2 Privileges
PRINCE originally granted the CREATE VIEW privilege to ARIEL.Revoked system privileges do not cause cascading revokes; only object priv-ilege revokes can do that
CREATE VIEW CA_ARTISTS AS SELECT * FROM MUSIC.ARTIST WHERE STATE_PROVINCE='CA';
We will now examine some rules about revoking privileges Usinggraphic examples, here are some key points to remember about how revok-ing of privileges works
23.2.2.1 Revoked System Privileges DO NOT Cascade
When you revoke a system privilege, the revoke affects only the user you arenaming and does not affect any objects or users created For example, SYS-TEM grants the CREATE USER privilege WITH ADMIN OPTION toASSISTANT Then ASSISTANT creates a user named INTERN andgrants her the CREATE USER privilege Now, INTERN creates anotheruser named JOE Figure 23.10 illustrates these events
Trang 223.2 Privileges 521
Chapter 23
Now, as the DBA, you decide that your assistant does not need to createusers at this point, so you revoke the CREATE USER privilege fromASSISTANT
ASSISTANT can no longer create users; however, the users she createdstill exist And, INTERN, who received the system privilege CREATEUSER from ASSISTANT, retains that privilege Figure 23.11 illustrates thisidea by showing that ASSISTANT cannot create a user, while INTERNcan create a user
23.2.2.2 Revoked Object Privileges DO Cascade
Revoking an object privilege does result in a cascading set of revoked leges For example, imagine that SYSTEM grants SELECT onMUSIC.ARTIST to ASSISTANT using the WITH GRANT OPTIONclause Then ASSISTANT grants the same object privilege to INTERNwho in turn grants the privilege (without the WITH GRANT OPTION)
privi-to JOE Figure 23.12 shows the scenario
After careful thought, you decide that your assistant no longer requiresthe SELECT privilege on the MUSIC.ARTIST table, so you revoke theprivilege The revoke actually cascades and revokes the privilege fromINTERN, and then it cascades again and revokes the privilege from JOE
Figure 23.11
ASSISTANT Failed to Create MATTHEW, but
INTERN Created
BETH.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 3522 23.3 Grouping Privileges Using Roles
Now, only SYSTEM can successfully query the MUSIC.ARTIST table.Figure 23.13 shows how this works
Remember that revoked system privileges do not cascade and revokedobject privileges do cascade
One of the more repetitive DBA tasks is that of granting the properprivileges to new users and maintaining privileges for all existing users Veryoften, a group of users has identical privileges The next section shows youhow to take advantage of this with roles Roles allow groupings of privilegesand subsequent granting of privilege groups with a single granting or revoke
of a role
A role is a set or grouping of object and/or system privileges that is assigned
a name Once a role is established, you can grant the role instead of ing all of the individual privileges to a user This capability saves a great deal
Trang 423.3 Grouping Privileges Using Roles 523
Chapter 23
Note: PL/SQL code blocks may not recognize database access through
roles Explicit object privileges may be required for PL/SQL PL/SQL iscovered in Chapter 24
23.3.1 Creating and Altering Roles
Figure 23.14 shows the syntax of the CREATE ROLE and ALTER ROLEcommands Options are identical for both commands Any user with theCREATE ROLE system privilege can create a role The SYSTEM user, ofcourse, has this privilege The DBA often grants this privilege to users whoown tables, so that users can create roles associated with their tables andgrant those roles to other users
A role that will contain sensitive privileges can be assigned a password.Any user who wants to use that role must provide the password (exceptwhen the role is one of the user’s default roles) You will find out moreabout default roles later At this stage, all we will do is lay some groundworkfor later and create two roles, substitute strings where appropriate
Figure 23.13
Revoking an Object
Privilege Cascades
to Other Users to
whom the Revokee
Granted the Same
Object Privilege.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 5524 23.3 Grouping Privileges Using Roles
CONNECT SYSTEM/password@OLTP;
CREATE ROLE MINIDBA;
CREATE ROLE MUSIC_ACCESS;
The MINIDBA role will be a highly privileged role, thus I amusing the ALTER ROLE command to restrict access using a pass-word
ALTER ROLE MINIDBA IDENTIFIED BY DBA#9876;
Note: The password is the only portion of a role that can be altered You can
add, change, or remove the password on a role If you want to change thename of a role, you must drop and then re-create it with the changed name
Once roles are created, privileges can be granted to them as if they areusers Then roles can be granted to users Once a user has a role granted, he
or she inherits all of the privileges assigned to that role
23.3.2 Granting and Revoking Privileges on Roles
Granting privileges to a role is exactly the same (syntax-wise) as grantingprivileges to a user Figures 23.5 and 23.9 show the syntax of granting andrevoking privileges to and from roles Roles can be granted to a user, a role,
or PUBLIC
Let’s grant some privileges First connect to the SYSTEM user
Figure 23.14
A New Role Does
Not Contain Any
Privileges at First.
Trang 623.3 Grouping Privileges Using Roles 525
Chapter 23
CONNECT SYSTEM/password@OLTP;
Now we give the MINIDBA role three system privileges that you wish
to delegate to an assistant DBA
GRANT CREATE USER, CREATE SESSION, CREATE ROLE
GRANT SELECT ON ARTIST TO MUSIC_ACCESS;
GRANT SELECT ON SONG TO MUSIC_ACCESS;
GRANT SELECT ON MUSICCD TO MUSIC_ACCESS;
GRANT SELECT, INSERT, UPDATE, DELETE
be logically grouped together under a single role
So we have added privileges to both roles and now wish to grant roles tousers The MUSIC user did not create any roles and does not have theGRANT ANY ROLE system privilege We have to connect to SYSTEMagain
CONNECT SYSTEM/password@OLTP;
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 7526 23.3 Grouping Privileges Using Roles
Let’s say that you want PRINCE to be allowed to use the MUSIC cation In addition, PRINCE will be allowed to grant the role to otherusers Grant the appropriate role to PRINCE using this command:
appli-GRANT MUSIC_ACCESS TO PRINCE WITH ADMIN OPTION;
Granting a role to a user has the same syntax as granting system leges; therefore, you use the WITH ADMIN OPTION when you want theuser to be able to grant the role to others
privi-We also decide that the MINIDBA role should have all privilegesgranted to the MUSIC_ACCESS role in addition to the system privilegesalready granted to it Grant the MUSIC_ACCESS role to the MINIDBArole
GRANT MUSIC_ACCESS TO MINIDBA;
Now, grant the MINIDBA role to ARIEL
GRANT MINIDBA TO ARIEL;
ARIEL has all privileges from both roles
Connect to PRINCE
CONNECT PRINCE/CHARMING@OLTP;
PRINCE is allowed to grant the MUSIC_ACCESS role He grants it toARIEL
GRANT MUSIC_ACCESS TO ARIEL;
After doing this, we realize that ARIEL already has theMUSIC_ACCESS role because it is included in the MINIDBA role SoPRINCE can revoke the redundant role
REVOKE MUSIC_ACCESS FROM ARIEL;
Trang 823.3 Grouping Privileges Using Roles 527
Chapter 23
Note: Roles can be granted to other roles, establishing groups of groupings
of privileges
23.3.3 Setting User Roles
A role, once assigned to a user, can be either enabled or disabled in theuser’s session By default, any role assigned to a user is enabled The DBAcan adjust which roles are enabled by default for each user when that userlogs in, using the ALTER USER command In addition, a user can enable arole using the SET ROLE command
The ALTER USER command syntax is shown in Figure 23.15 TheALTER USER command has many other uses Figure 23.15 shows onlyportions of syntax catering to user default roles
When a user starts a session (connects to a database), roles are enabledaccording to settings made by the DBA using the ALTER USER command
A user can modify his or her session and change the enabled role set usingthe SET ROLE command Figure 23.16 shows the syntax for the SETROLE command
Let’s show some use of role allocation First, reconnect to SYSTEMusing this command:
CONNECT SYSTEM/password@OLTP;
Figure 23.15
Modify a User’s Default Roles with
ALTER USER.
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 9528 23.3 Grouping Privileges Using Roles
All roles assigned to a user start out enabled by default, including roleswith passwords If you want the user to be required to use the passwordbefore enabling the role, you must remove the role from the user’s list ofdefault roles The MINIDBA role has a password and has been granted toARIEL Remove this role from ARIEL’s default roles
ALTER USER ARIEL DEFAULT ROLE ALL EXCEPT MINIDBA;
Now connect to ARIEL replacing the variable as usual
CONNECT ARIEL/MERMAID@OLTP;
ARIEL cannot perform any tasks that need the system privileges found
in the MINIDBA role (such as creating new users), because the role is abled She enables the MINIDBA role by using the SET ROLE command,including the appropriate password
dis-SET ROLE MINIDBA IDENTIFIED BY DBA#9876;
Note: Be careful to include all of the roles you wish to enable in your SET
Trang 1023.3 Grouping Privileges Using Roles 529
Chapter 23
Roles not included in the SET ROLE command become disabled Forexample, let’s say you have three roles enabled by default (VIEWMUSIC,UPDATEMUSIC, and DELETEMUSIC) and one role (INSERTMUSIC)disabled by default If the command SET ROLE INSERTMUSIC is exe-cuted, you will enable the INSERTMUSIC role and disable the VIEW-MUSIC, UPDATEMUSIC, and DELETEMUSIC roles Oracle Database
10g provides some predefined roles you can use if you wish There are many
predefined roles Some of them are listed as follows:
CONNECT System privileges needed to log on and work as a
data-base developer Privileges include CREATE TABLE, CREATEVIEW, CREATE SESSION, CREATE CLUSTER, and so on Eachoperating system has a slightly different group of privileges, but gen-erally, you have all you need to do basic database work
RESOURCE System privileges needed for other database
develop-ment, such as creating types Privileges include CREATE TYPE andCREATE PROCEDURE Like the CONNECT role, the exact priv-ileges vary from system to system
SELECT_CATALOG_ROLE Allows access to data dictionary
metadata and performance views, the catalog
Use these to help you get started in administering your database Oraclerecommends, however, that you study the underlying privileges and createyour own roles for most tasks The CONNECT and RESOURCE rolesmay not be created automatically in future releases of Oracle
23.3.4 Dropping Roles
This final section on roles involves removing roles Whenever you remove arole, it is revoked from all users who currently have the role Syntax for theDROP ROLE command is shown in Figure 23.17
Roles are an excellent way to consolidate privileges needed for runningapplications
Trang 11530 23.4 Metadata Views
This section simply describes metadata views applicable to users, privileges,and roles Chapter 19 describes the basis and detail of Oracle Databasemetadata views
USER_USERS Information on the logged-in user ALL_USERS
and DBA_USERS detail information for all users currently existing
in the database
USER_SYS_PRIVS Granted system privileges.
USER_TAB_PRIVS[_MADE|RECD] All object privileges (granted
to and from plus owned) MADE and RECD implies granted object
privileges and grantee object privileges, respectively
Note: The term grantee implies that a user has been granted a privilege by
another user
USER_COL_PRIVS[_MADE|RECD] As for USER_TAB_PRIVS
but as applied to specific columns only, not entire tables
ROLE_PRIVS Roles granted to a user, both enabled and disabled.
USER_ROLE_PRIVS Roles granted to the connected user, both
enabled and disabled
SESSION_ROLES A connected session’s enabled roles.
ROLE_ROLE_PRIVS Roles granted to other roles.
ROLE_TAB_PRIVS Object privileges granted to roles.
ROLE_SYS_PRIVS System privileges granted to roles.
DBA_ROLE_PRIVS Roles granted to users and other roles, who or
which role granted it to the user or role, respectively, and whether theuser has WITH ADMIN OPTION for the role
This chapter has described security and controlling database access usingusers, both system and object privileges, and finally privilege groupingsusing roles The next chapter, the final chapter in this book, digresses fromOracle SQL more so than this chapter, examining the very basics of Pro-gramming Language/SQL (PL/SQL)
Trang 12What are variables and PL/SQL datatypes?
What are procedures, functions, triggers, and packages?
How is data retrieved from the database using PL/SQL?
What programming control structures exist in PL/SQL?
What is dynamic or generic SQL?
This chapter covers basic reference material and examples on how towrite programs in PL/SQL It should be noted that the PL/SQL is a wrap-per extension of Oracle SQL in that its original purpose was that of data-base access only However, in recent years, PL/SQL has been expandedvoluminously to become more of a programming language
PL/SQL is an acronym for Programming Language/SQL StructuredQuery Language (SQL) is a scripting language A scripting language usuallydoes not allow any dependencies between separate, following commands
Note: This is not strictly true for all scripting languages Even thoughUNIX shell scripting has many features, attempting to write complex appli-cations using only UNIX shell scripting can lead to expensive problems
Chap24.fm Page 531 Thursday, July 29, 2004 10:16 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 13532 24.2 Why Is PL/SQL a Programming Language?
PL/SQL extends SQL with programming controls and features such asprocedures, variables, and control structures Let’s begin the meat of thischapter by asking: Why is PL/SQL classified as a programming language?
PL/SQL is a programming language because, unlike SQL, it allows dencies to exist between multiple SQL commands, within the same block
depen-of code In Oracle SQL, each SQL statement cannot pass a result on toanother SQL statement or control structure, but PL/SQL can Also, per-haps more important, a programming language block structure allows oneprocedure to call another, allowing for a modular, compartmentalized, orperhaps even pseudo-object hierarchical programming structure
Therefore, PL/SQL is a programming language because it contains theability to do the following things:
Allows dependencies between commands within the same block ofcode
Allows for parameter passing up and down code block hierarchies Itallows for structure, namely modular
Contains a definition of variable scope across code block hierarchies,strict data typing, and allows use of commonly used programmingcontrol structures
The downside of PL/SQL is that it should be primarily used as a base access programming language PL/SQL does not perform well as anumber cruncher like C or Java
data-One more point to make is as follows: PL/SQL is becoming increasinglymore capable as an object-like programming language, where the Oraclerelational database allows for hierarchical object data structures It tries toanyway For what it is worth in my experienced opinion, I would avoidusing Oracle Database or PL/SQL to manage objects If you want to useobject methodologies to manage complexity, put it at the application levelusing something like Java or use an object database
Chap24.fm Page 532 Thursday, July 29, 2004 10:16 PM
Trang 1424.2 Why Is PL/SQL a Programming Language? 533
Chapter 24
24.2.1 Blocks and Exception Trapping
A block of code is a group of lines of SQL or PL/SQL code enclosedbetween BEGIN and END statements A block of code is parsed and exe-cuted after the END statement is submitted using the front slash (/) charac-ter The following SQL block consists of a variable declaration sectionfollowed by a BEGIN to END code block See the result in Figure 24.1.This block of code queries the ARTIST table for the ARTIST_ID of SherylCrow It stores the ARTIST_ID in a variable and then uses the variable tofind the title of the first song of Sheryl Crow in the SONG table It storesthe title in another variable Then it displays the title and completes
SET SERVEROUTPUT ON;
DECLARE vARTIST_ID ARTIST.ARTIST_ID%TYPE;
vTITLE SONG.TITLE%TYPE;
BEGIN SELECT ARTIST_ID INTO vARTIST_ID FROM ARTIST WHERE NAME='Sheryl Crow';
SELECT TITLE INTO vTITLE FROM SONG WHERE ARTIST_ID = vARTIST_ID AND ROWNUM = 1;
Note: The statement SET SERVEROUTPUT ON is essential for theproper functioning of the DBMS_OUTPUT.PUT_LINE packaged proce-dure DBMS_OUTPUT is an Oracle-provided package The PUT_LINEprocedure within that package sends a line to the output SET SERVER-OUTPUT OFF switches output off
Note: %TYPE sets a variable to the datatype of the specifiedTABLE.COLUMN
Chap24.fm Page 533 Thursday, July 29, 2004 10:16 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 15534 24.2 Why Is PL/SQL a Programming Language?
The block of code in Figure 24.1 is an anonymous PL/SQL block,which is effectively an unnamed procedure without parameters It is exe-cuted by the front slash (/) character, is not stored, and thus cannot be exe-cuted again as a stored, named object
The last two lines in Figure 24.1 before the block END statement prise an error exception trap Any errors occurring between the BEGINstatement and the EXCEPTION statement will cause control to pass to theEXCEPTION trap, which executes the RAISE statement The RAISEstatement does nothing in this procedure, passing an exception to the call-ing block If no calling block exists, then an error called unhandled exception
com-will be returned to the calling application In our case, SQL*Plus sheet is the calling application
Work-24.2.2 Procedures, Functions, Triggers, and Packages
Unlike an anonymous block, stored procedures are named, compiled, andstored in the database They can be executed repeatedly in the future byexecuting the procedure name PL/SQL stored objects include procedures,functions, triggers, and packages What are the differences between thesefour compiled, executable database objects? They are as follows:
Procedure Allows by value and by reference parameters with noreturn value
Figure 24.1
PL/SQL Block
Structure and
Exception Trapping.
Chap24.fm Page 534 Thursday, July 29, 2004 10:16 PM
Trang 1624.2 Why Is PL/SQL a Programming Language? 535
Chapter 24
Function Like a procedure but allows a return value
Trigger No transactional termination commands allowed and cuted automatically by database event occurrences Triggers areknown as event-driven procedures
exe- Package Groups multiple procedures and functions together intoblocked units
24.2.2.1 Using Named Procedures
The following named procedure is a slightly more sophisticated copy of theanonymous procedure presented previously The procedure now has aname, accepts a parameter, is stored in the database, and can be executedrepeatedly by executing the procedure name as shown in the followingscript The result is shown in Figure 24.2
CREATE OR REPLACE PROCEDURE GETSONG (pARTIST IN VARCHAR2) AS vARTIST_ID ARTIST.ARTIST_ID%TYPE;
vTITLE SONG.TITLE%TYPE;
BEGIN SELECT ARTIST_ID INTO vARTIST_ID FROM ARTIST WHERE NAME=pARTIST;
SELECT TITLE INTO vTITLE FROM SONG WHERE ARTIST_ID = vARTIST_ID AND ROWNUM = 1;
EXEC GETSONG('Sheryl Crow');
EXEC GETSONG('Avril Lavigne');
SET SERVEROUTPUT OFF;
24.2.2.2 Using Functions
Following are two versions of a function used previously in this book Thisfunction will split a string time value of HH:SS into its hours and secondsconstituent parts and convert them to a real number
CREATE OR REPLACE FUNCTION GETTIME(pTIME IN VARCHAR2) RETURN NUMBER IS
variable declaration section
Chap24.fm Page 535 Thursday, July 29, 2004 10:16 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 17536 24.2 Why Is PL/SQL a Programming Language?
vLEN INTEGER DEFAULT 0;
vSPLIT INTEGER DEFAULT 0;
vHOURS INTEGER DEFAULT 0;
vSECONDS INTEGER DEFAULT 0;
BEGIN execution section vSPLIT := INSTR(pTIME,':');
vLEN := LENGTH(pTIME);
vHOURS := TO_NUMBER(SUBSTR(pTIME,1,vSPLIT-1));
vSECONDS := TO_NUMBER(SUBSTR(pTIME, vSPLIT+1,vLEN-vSPLIT));
RETURN vHOURS+(vSECONDS/60);
EXCEPTION WHEN OTHERS THEN exception trap section RETURN 0;
Chap24.fm Page 536 Thursday, July 29, 2004 10:16 PM
Trang 1824.2 Why Is PL/SQL a Programming Language? 537
EXCEPTION WHEN OTHERS THEN RETURN 0;
END;
/
I can execute the GETTIME function on the SONG tablePLAYING_TIME column (SONG.PLAYING_TIME) using the followingscript The result is shown in Figure 24.3
SELECT PLAYING_TIME, GETTIME(PLAYING_TIME) FROM SONG WHERE PLAYING_TIME IS NOT NULL;
Note: The GETTIME function is also known as a custom-written or defined function
user-24.2.2.3 Using Triggers
Here are some simple example triggers The first trigger detects insertions tothe ARTIST table, the second updates, and the third deletions Figure 24.4shows the response from an INSERT, an UPDATE, and a DELETE com-mand, one after the other
CREATE OR REPLACE TRIGGER iARTIST AFTER INSERT ON ARTIST FOR EACH ROW BEGIN
DBMS_OUTPUT.PUT_LINE('New Artist '||:NEW.NAME||' added.');
Chap24.fm Page 537 Thursday, July 29, 2004 10:16 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 19538 24.2 Why Is PL/SQL a Programming Language?
EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLERRM(SQLCODE));
RAISE;
END;
/ CREATE OR REPLACE TRIGGER uARTIST AFTER UPDATE OF NAME ON ARTIST FOR EACH ROW BEGIN
DBMS_OUTPUT.PUT_LINE('Artist changed from '
DBMS_OUTPUT.PUT_LINE('Artist '||:OLD.NAME
||' has been deleted');
EXCEPTION WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE(SQLERRM(SQLCODE));
Trang 2024.2 Why Is PL/SQL a Programming Language? 539
Chapter 24
/ SET SERVEROUTPUT ON;
INSERT INTO ARTIST(ARTIST_ID,NAME) VALUES(100,'Robert Alan Zimmerman');
UPDATE ARTIST SET NAME='Bob Dylan' WHERE NAME='Robert Alan Zimmerman';
DELETE FROM ARTIST WHERE NAME='Bob Dylan';
SET SERVEROUTPUT OFF;
24.2.2.4 Using Packages
Packages can be used to group commonly stored PL/SQL units into a singlechunk of code A package must have a declaration section and a body sec-tion The declaration simply defines named units within the package, andthe package body contains the actual procedures The following script is asimple package converting temperatures between degrees Fahrenheit (F˚),degrees Celsius (C˚), and degrees Kelvin (K˚) Example executions of thevarious functions are shown in Figure 24.5
CREATE OR REPLACE PACKAGE TEMPERATURE AS FUNCTION cTOf(c VARCHAR2 DEFAULT 0) RETURN VARCHAR2; FUNCTION fTOc(f VARCHAR2 DEFAULT 0) RETURN VARCHAR2;
Figure 24.4
Executing Triggers
from DML Commands.
Chap24.fm Page 539 Thursday, July 29, 2004 10:16 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 21540 24.2 Why Is PL/SQL a Programming Language?
FUNCTION fTOK(f VARCHAR2 DEFAULT 0) RETURN VARCHAR2; FUNCTION KTOf(K VARCHAR2 DEFAULT 0) RETURN VARCHAR2; FUNCTION cTOK(c VARCHAR2 DEFAULT 0) RETURN VARCHAR2; FUNCTION KTOc(K VARCHAR2 DEFAULT 0) RETURN VARCHAR2; END;
/ CREATE OR REPLACE PACKAGE BODY TEMPERATURE AS FUNCTION cTOf(c VARCHAR2 DEFAULT 0) RETURN VARCHAR2 AS BEGIN
RETURN TO_CHAR(c)||'C˚ = '||ROUND(32+((9/
Now let’s look into variables and datatypes for PL/SQL
Chap24.fm Page 540 Thursday, July 29, 2004 10:16 PM
Trang 2224.3 Variables and Datatypes in PL/SQL 541
Chapter 24
PL/SQL contains all of the predefined datatypes included in SQL, asexplained in Chapter 16, plus some additional datatypes Some of theseadditional datatypes are listed as follows:
NUMBER Datatypes There are numerous NUMBER subtypesprovided for ANSI standard compliance These subtypes will all con-vert to NUMBER or FLOAT datatypes both for Oracle table col-umns and internally in PL/SQL For example, INTEGER andSMALLINT
BINARY_INTEGER Stores a signed integer value There are varioussubtypes
BOOLEAN Stores a TRUE, FALSE, or null value
RECORD Composite structure similar to a VARRAY or TABLEdatatype allowing the creation of a table row structure in memory.The following line uses ROWTYPE to duplicate the column struc-ture of an ARTIST table row into the RECORD called RARTIST
Figure 24.5
Using a Package to
Group Procedures.
Chap24.fm Page 541 Thursday, July 29, 2004 10:16 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 23542 24.3 Variables and Datatypes in PL/SQL
RARTIST ARTIST%ROWTYPE;
In the following code, a new record structure is built using onenew field (ID), the ARTIST.NAME field, and the SONG.NAMEfield A RECORD datatype is then declared as having the structure
of the new type, TARTISTSONGS
TYPE TARTISTSONGS IS RECORD (ID INTEGER , ARTISTS ARTIST.NAME%TYPE
Associative Arrays Associative arrays are currently only allowed inPL/SQL and not Oracle SQL An associative array is a dynamic arraymuch like a nested table object (see Chapter 16) The only difference
is that an associative array is indexed and thus capable of much betterperformance than a nested table The following script snippet showshow an associative array is declared in PL/SQL as opposed toVARRAYs and nested tables:
DECLARE TYPE tTable IS TABLE OF VARCHAR2(32);
TYPE tVARRAY IS VARRAY(100) OF INTEGER;
TYPE tITable IS TABLE OF VARCHAR2(32) INDEX BY BINARY_INTEGER;
vPointer tTable;
vArray tVARRAY;
vIndexedPointer tITable;
BEGIN NULL;
END;
/
Chap24.fm Page 542 Thursday, July 29, 2004 10:16 PM
Trang 24In PL/SQL, cursors can be created as programming data structures Cursorscan be used for queries returning one or many rows and can be of twotypes: implicit and explicit cursors An implicit cursor is declared automati-cally by PL/SQL, and an explicit cursor is declared by the programmer Anexplicit cursor gives more control to the programmer.
24.4.1 Explicit Cursors
An explicitly declared cursor allows more programmer access to a cursor, foreach row in that cursor, using the cursor OPEN, FETCH, and CLOSEcommands
What is an explicit cursor? Let’s explain it in steps: the first step is todeclare a cursor This example names the cursor CARTIST The query(SELECT * FROM ARTIST) retrieves rows of data and places them in thecursor’s memory area At the same time, we declare a RECORD type tocontain each row retrieved We use the record type called RARTIST, seenbefore in this chapter, to retrieve each row of data from the cursor
SET SERVEROUTPUT ON;
DECLARE CURSOR CARTIST IS SELECT * FROM ARTIST;
RARTIST ARTIST%ROWTYPE;
The second step is to open the cursor This parses the query and loadsthe first portion of rows into the cursor in preparation for retrieval by theprogram:
BEGIN OPEN CARTIST;
Chap24.fm Page 543 Thursday, July 29, 2004 10:16 PM
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Trang 25544 24.4 Retrieving Data in PL/SQL
Now we loop through the open cursor, selecting each row There will bemore about loops later in this chapter This loop has three commands Thefirst one places the next row from the cursor into the RARTIST record vari-able The second command causes the looping to end if the status of thecursor is NOTFOUND (meaning there are no rows left to retrieve.) Thethird line places a line on the screen that displays the artist name This line
is executed only if there was a row retrieved from the cursor The three linesare repeated for every row retrieved from the cursor:
LOOP FETCH CARTIST INTO RARTIST;
EXIT WHEN CARTIST%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(RARTIST.NAME);
END LOOP;
Do not forget to close your cursor! Explicit cursors should be closed assoon as they are no longer needed to improve performance, prevent lockingissues, and ensure that cursor limits are not reached
CLOSE CARTIST;
END;
/ SET SERVEROUTPUT OFF;
The execution of the pieces of the anonymous procedure loopingthrough the explicit cursor just described is shown in Figure 24.6
There are other variations of how explicit cursors can be coded, but we
do not need to go into any further detail
24.4.2 Implicit Cursors
Every SQL statement both in SQL and inside a PL/SQL block not declaredexplicitly as a cursor is an implicit cursor An implicit cursor is opened andclosed by SQL or PL/SQL and is used to process INSERT, UPDATE,DELETE, and SELECT statements A special type of implicit cursor exclu-sive to PL/SQL is called a cursor FOR loop A cursor FOR loop is animplicit cursor on the basis that it does not require use of the OPEN,FETCH, and CLOSE statements