Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

307
Introduction to Oracle: SQL and PL/SQL Using Procedure Builder Volume Four S Participant Guide Edition 1.1 M03992 T1001E11

description

Introduction To Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide.pdf

Transcript of Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

Page 1: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� �� ��� �� ������ ������ ���� ���������� ����� ��� ���� � �������� ����

������� ���

���

������

Page 2: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

Authors

Neena KochharDebby Kramer

Technical Contributorsand Reviewers

Christian BauwensDebra BowmanLenny BrunsonJackie CollinsRalf DurbenBrian FryAnthony HolbrookKarlene JensenSarah JonesGlenn MaslenSundar NagarathnamSandra SchrickUlrike SchwinnRosemarie TrumanJenny TsaiLaura Van Deusen

Publishers

Stephanie JonesKimberly LeeJennifer RobertsonMark Turangan

��������� �������� ������������ ��� � ����� ��� ������ ���������

���� ��� !�������� �������� ����������� ��"��!����� �" ������ �����������# �� ��

�������� ���� � ������� �����!��� ���������� ������������ �� �� ��� ������$

� �� ��� �� ���� ��������� %� ��������� ��&� '������ ����������� �" ��� ��"�&���

�� �����%����� (" ���� ��� !�������� �� ��������� �� � )�*� +�����!��� ������ �"

��� ,�����!��� �" ,�"����� ���� �� �� ��������� &��� '��������� '����� ��� ��� "��$

��&��� ������ �� �������%��-

�������� �� �� ������

)��� � ��������� �� ������� �� %� ��� +�����!��� �� � %.��� �� ������������ "��

��!!������ ��!� ��� ��"�&��� ��� ����� %� ���!�� �� %� '��������� '����� ��"�$

&��� ���� /������ ��&� ��� �� ��� "���� �� � %��������� 0�1 0�1 0��1 �" ,/�'*

2 � 3$3��� '����� �� ��������� ,��� ��� ��!� ��� *�"�&��� 0����%�� ��441�

���� !������� �� ��� ������� �" �� !�� ��� %� ������ �� ��� "��! �� %� ��� !����

&���� � ��� �5����� ����� &������ ���!������ �" ���6����&��� �� ������ *�������

��� � �"������ ������������ ��� ����� ������� �� � ��������� �" ��������� ��& ���

!�� ��� �� �� ����� ���7�� ���!���� ����������

(" ���� ��� !�������� �� ��������� �� �)�*� +�����!��� ������ ��� &����� ��� ,�$

����!��� �" ,�"����� ���� �� �� ��������� &��� 8'��������� '������9 �� ��"���� ��

/�' 2 � 3$�:� '����� �� ,���$+������� ���� ���� ��������� ((( 0; �� ��431�

��� ��"��!����� �� ���� ��� !��� �� � %.��� �� ������ &���� � ������� (" �� "���

��� ���%��!� �� ��� ��� !��������� ������ ������ ���! �� &������ �� 6����&���

�� ������ *�������� ������ ������������ 2 ������ <��=&��� >�5 �2�4�� '��$

&���*������ ���:�2������������������ ���� ���&������ ���� ���� ��� !���

�� ����� "����

*?@A<� �� <@7*?@� <����� �� > ������ ,��������7 � ������3 *������ ������

*������ ,���������7 � ��� ,�������7 ��� �����!��=� �� ���������� �����$

!��=� �" ������ ������������

��� ����� ���� ��� �� ��!���� ��!�� ��� ��� "�� ������"������� � ������ �����

��� !�� %� �����!��=� �" ����� ���������� �&�����

Page 3: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� �����

Page 4: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

Page 5: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���

�������

There is often more than one way to achieve any result in SQL. Where possible, thealternatives have been identified in these solutions. The performance benefits, if any,are also mentioned. If you want to analyze any of the statements, refer to SQL*Trace.This facility allows you to see how the SQL statement is being interpreted at thedatabase level.

For more information, seeOracle7 Server SQL Reference, Release 7.3 and Oracle7 Server AdministratorsGuide.

Page 6: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

�������� � �����

1. SQL commands are always held in a buffer.

� True

2. SQL*Plus commands assist with querying data.

� FalseSQL*Plus commands allow you to format resulting data and control files.Only SQL accesses the database.

3. Show the structure of the S_DEPT table. Select all information from theS_DEPT table.

SQL> DESCRIBE s_dept

Name Null? Type ---------------------------- -------- ---- ID NOT NULL NUMBER(7) NAME NOT NULL VARCHAR2(25) REGION_ID NUMBER(7)

SQL> SELECT *2 FROM s_dept;

ID NAME REGION_ID--------- ------------------------- --------- 10 Finance 1 31 Sales 1 32 Sales 2 33 Sales 3 34 Sales 4 35 Sales 5 41 Operations 1 42 Operations 2 43 Operations 3 44 Operations 4 45 Operations 5 50 Administration 1

12 rows selected.

Page 7: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���

�������� � ����� ���������

4. Show the structure of the S_CUSTOMER table. Using this table, perform thefollowing actions:

SQL> DESCRIBE s_customer

Name Null? Type -------------------------- -------- ---- ID NOT NULL NUMBER(7) NAME NOT NULL VARCHAR2(50) PHONE VARCHAR2(25) ADDRESS VARCHAR2(400) CITY VARCHAR2(30) STATE VARCHAR2(20) COUNTRY VARCHAR2(30) ZIP_CODE VARCHAR2(75) CREDIT_RATING VARCHAR2(9) SALES_REP_ID NUMBER(7) REGION_ID NUMBER(7) COMMENTS VARCHAR2(255)

a. Retrieve all information from the S_CUSTOMER table.

SQL> SELECT *2 FROM s_customer;

Continued

Page 8: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������

�������� � ����� ���������

4.—continued

b. Display the name and phone number for each customer.

SQL> SELECT name, phone2 FROM s_customer;

NAME PHONE----------------------------------- --------------Unisports 55-2066101Simms Atheletics 81-20101Delhi Sports 91-10351Womansport 1-206-104-0103Kam’s Sporting Goods 852-3692888Sportique 33-2257201Sweet Rock Sports 234-6036201Muench Sports 49-527454Beisbol Si! 809-352689Futbol Sonora 52-404562Kuhn’s Sports 42-111292Hamada Sport 20-1209211Big John’s Sports Emporium 1-415-555-6281Ojibway Retail 1-716-555-7171Sporta Russia 7-3892456

15 rows selected.

Continued

Page 9: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��!

�������� � ����� ���������

4.—continued

c. Display the phone number and name for each customer, with phone numberappearing first.

SQL> SELECT phone, name2 FROM s_customer;

PHONE NAME-------------------- -------------------------55-2066101 Unisports81-20101 Simms Atheletics91-10351 Delhi Sports1-206-104-0103 Womansport852-3692888 Kam’s Sporting Goods33-2257201 Sportique234-6036201 Sweet Rock Sports49-527454 Muench Sports809-352689 Beisbol Si!52-404562 Futbol Sonora42-111292 Kuhn’s Sports20-1209211 Hamada Sport1-415-555-6281 Big John’s Sports Emporium1-716-555-7171 Ojibway Retail7-3892456 Sporta Russia

15 rows selected.

Page 10: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������"

�������� � �����

1. You cannot order by a column that you have not selected.

� False

2. This SELECT statement will execute successfully.

� True

SQL> SELECT last_name, title, salary Ann_sal2 FROM s_emp3 WHERE last_name = ’Dancs’;

3. This SELECT statement will execute successfully.

� True

SQL> SELECT *2 FROM s_emp3 WHERE salary*12 = 9600;

4. There are four coding errors in this statement. Can you identify them?

SQL> SELECT id, last_name, 2 salary x 12 ANNUAL SALARY3 FROM s_emp4 WHERE sal > 30005 AND start_date LIKE %84;

� No SAL column in existence (WHERE clause).

� The ANNUAL SALARY alias cannot include spaces. Alias should readANNUAL_SALARY or be enclosed by quotation marks.

� The multiplication operator is *, not x as shown in line 2.

� All values when using the LIKE operator should be enclosed within singlequotation marks. The value should read ‘%84’ in line 5.

Page 11: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��#

�������� � ����� ���������

5. Use the S_CUSTOMER table to perform the following actions.

a. Create a query to display the name, customer number, and credit rating for allcompanies represented by sales representative 11. Save your SQL statement toa file named p2q5.

SQL> SELECT name, id, credit_rating2 FROM s_customer3 WHERE sales_rep_id = 114

SQL> SAVE p2q5

Created file p2q5

b. Run your query in the file p2q5.

SQL> START p2q5

NAME ID CREDIT_RA------------------------------ --------- ---------Womansport 204 EXCELLENTBeisbol Si! 209 EXCELLENTBig John’s Sports Emporium 213 EXCELLENTOjibway Retail 214 POOR

Continued

Page 12: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$

�������� � ����� ���������

5.—continued

c. Load p2q5 into the SQL buffer. Name the column headings Company,Company ID, and Rating. Rerun your query. Resave your query as p2q5.

� Solution file: p2q5.sql

SQL> GET p2q5

1 SELECT name, id, credit_rating 2 FROM s_customer 3* WHERE sales_rep_id = 11

SQL> 1 SELECT name ”Company”, id ”Company ID”,SQL> i credit_rating ”Rating”SQL> RUN

1 SELECT name ”Company”, id ”Company ID”, 2 credit_rating ”Rating” 3 FROM s_customer 4* WHERE sales_rep_id = 11

Company Company ID Rating------------------------------ ---------- ---------Womansport 204 EXCELLENTBeisbol Si! 209 EXCELLENTBig John’s Sports Emporium 213 EXCELLENTOjibway Retail 214 POOR

SQL> SAVE p2q5 REPLACE

Wrote file p2q5

Continued

Page 13: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

5.—continued

d. Retrieve p2q5 into the SQL buffer. Order the query results in descendingorder by customer number. Run your query.

SQL> GET p2q5

1 SELECT name ”Company”, id ”Company ID”, 2 credit_rating ”Rating” 3 FROM s_customer 4* WHERE sales_rep_id = 11

SQL> i ORDER BY 2 DESCSQL> /

Company Company ID Rating------------------------------ ---------- ---------Ojibway Retail 214 POORBig John’s Sports Emporium 213 EXCELLENTBeisbol Si! 209 EXCELLENTWomansport 204 EXCELLENT

6. Show the structure of the S_EMP table.

SQL> DESCRIBE s_emp

Name Null? Type -------------------------- -------- ---- ID NOT NULL NUMBER(7) LAST_NAME NOT NULL VARCHAR2(25) FIRST_NAME VARCHAR2(25) USERID NOT NULL VARCHAR2(8) START_DATE DATE COMMENTS VARCHAR2(255) MANAGER_ID NUMBER(7) TITLE VARCHAR2(25) DEPT_ID NUMBER(7) SALARY NUMBER(11,2) COMMISSION_PCT NUMBER(4,2)

Page 14: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

6.—continued

a. Display the user name for employee 23.

SQL> SELECT userid2 FROM s_emp3 WHERE id = 23;

USERID--------rpatel

b. Display the first name, last name, and department number of the employees indepartments 10 and 50 in alphabetical order of last name. Merge the firstname and last name together, and title the column Employees.

SQL> SELECT first_name||’ ’||last_name2 ”Employees”, dept_id3 FROM s_emp4 WHERE dept_id IN (10,50)5 ORDER BY last_name;

Employees DEPT_ID------------------------------------ ---------Mark Quick-To-See 10Audry Ropeburn 50Carmen Velasquez 50

Continued

Page 15: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

6.—continued

c. Display all employees whose last names contain an “s”.

� This solution is not quite complete because names that contain a capitalS do not appear in this list. In a later lesson, you will see how to changeyour query into a case-insensitive query.

SQL> SELECT first_name, last_name 2 FROM s_emp 3 WHERE last_name like ’%s%’;

FIRST_NAME LAST_NAME------------------------- ------------------------Carmen VelasquezAndre DumasBela Dancs

d. Display the user names and start date of employees hired between May 5,1990 and May 26, 1991. Order the query results by start date ascending order.

SQL> SELECT userid, start_date2 FROM s_emp3 WHERE start_date BETWEEN ’05-may-90’4 AND ’26-may-91’5 ORDER BY start_date;

Continued

Page 16: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

6d.—continued

USERID START_DAT-------- ---------rmenchu 14-MAY-90cmagee 14-MAY-90rpatel 17-OCT-90echang 30-NOV-90murguhar 18-JAN-91anozaki 09-FEB-91ysedeghi 18-FEB-91mhavel 27-FEB-91bdancs 17-MAR-91sschwart 09-MAY-91amarkari 26-MAY-91

11 rows selected.

7. Use the S_EMP table to perform the following actions.

a. Write a query to show the last name and salary of all employees who are notmaking between 1000 and 2500 per month.

SQL> SELECT last_name, salary2 FROM s_emp3 WHERE salary NOT BETWEEN 1000 AND 2500;

LAST_NAME SALARY------------------------- ---------Smith 940Patel 795Newman 750Markarian 850Chang 800Patel 795Dancs 860

7 rows selected.

Continued

Page 17: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

7.—continued

b. List the last name and salary of employees who earn more than 1350 who arein department 31, 42, or 50. Label the last name column Employee Name, andlabel the salary column Monthly Salary.

SQL> SELECT last_name ”Employee Name”,2 salary ”Monthly Salary”3 FROM s_emp4 WHERE salary > 13505 AND dept_id IN (31, 42, 50);

Employee Name Monthly Salary------------------------- --------------Velasquez 2500Nagayama 1400Ropeburn 1550Magee 1400

c. Display the last name and start date of every employee who was hired in1991.

SQL> SELECT last_name, start_date2 FROM s_emp3 WHERE start_date LIKE ’%91’;

Continued

Page 18: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

�������� � ����� ���������

7c.—continued

LAST_NAME START_DAT------------------------- ---------Nagayama 17-JUN-91Urguhart 18-JAN-91Havel 27-FEB-91Sedeghi 18-FEB-91Dumas 09-OCT-91Nozaki 09-FEB-91Patel 06-AUG-91Newman 21-JUL-91Markarian 26-MAY-91Dancs 17-MAR-91Schwartz 09-MAY-91

11 rows selected.

d. Display the full name of all employees with no manager.

SQL> SELECT first_name, last_name2 FROM s_emp3 WHERE manager_id IS NULL;

FIRST_NAME LAST_NAME------------------------- -------------------------Carmen Velasquez

Page 19: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!

�������� � ����� ���������

8. Show the structure of the S_PRODUCT table.

SQL> DESCRIBE s_product

Name Null? Type ------------------------- -------- ---- ID NOT NULL NUMBER(7) NAME NOT NULL VARCHAR2(50) SHORT_DESC VARCHAR2(255) LONGTEXT_ID NUMBER(7) IMAGE_ID NUMBER(7) SUGGESTED_WHLSL_PRICE NUMBER(11,2) WHLSL_UNITS VARCHAR2(25)

a. Alphabetically display all products having a name beginning with Pro.

SQL> SELECT name2 FROM s_product3 WHERE name LIKE ’Pro%’;

NAME--------------------------------------------------Pro Curling BarPro Ski BootPro Ski PoleProstar 10 Pound WeightProstar 100 Pound WeightProstar 20 Pound WeightProstar 50 Pound WeightProstar 80 Pound Weight

8 rows selected.

Continued

Page 20: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"

�������� � ����� ���������

8.—continued

b. Display all product names and short descriptions for all descriptionscontaining the word bicycle.

� Results have been formatted.

SQL> SELECT name, short_desc2 FROM s_product3 WHERE short_desc LIKE ’%bicycle%’

NAME SHORT_DESC------------------------- --------------------Grand Prix Bicycle Road bicycleHimalaya Bicycle Mountain bicycleGrand Prix Bicycle Tires Road bicycle tiresHimalaya Tires Mountain bicycle tires

c. Display all short descriptions. Compare the results from Exercise 10b. Didyour response in Exercise 10b return all descriptions containing “bicycle”?

� No, not all words containing “bicycle” were returned because theWHERE clause is case-sensitive. In a later lesson, you will see how toremove the case-sensitivity.

SQL> SELECT short_desc2 FROM s_product3 ORDER BY 1;

Continued

Page 21: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#

�������� � ����� ���������

8c.—continued

SHORT_DESC---------------------------------------------Advanced ski bootAdvanced ski poleBaseballBatting helmetBeginner’s ski bootBeginner’s ski poleBicycle helmetCatcher’s gloveCurling barEighty pound weightElbow pads, pairFifty pound weightInfielder’s gloveIntermediate ski bootIntermediate ski poleJunior soccer ballKnee pads, pairMountain bicycleMountain bicycle tiresOne hundred pound weightOutfielder’s gloveRoad bicycleRoad bicycle tiresStraight barTen pound weightThirty inch batThirty-six inch batThirty-two inch batTire pumpTwenty pound weightWater bottleWorld cup netWorld cup soccer ball

33 rows selected.

Page 22: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$

�������� � �����

1. Single row functions work on many rows to produce a single result.

� FalseSingle row functions work for each row selected by the query and return oneresult per row.

2. You can use all of the arithmetic operators on date values.

� FalseAdditional and subtraction are the only operators that can be used.

3. What is the name of the pseudo column that holds the current date?

� SYSDATE

Page 23: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

4. Display the employee number, last name, and salary increased by 15% andexpressed as a whole number.

SQL> SELECT id, last_name, ROUND(salary * 1.15)2 FROM s_emp;

ID LAST_NAME ROUND(SALARY*1.15)------ ------------ ------------------ 1 Velasquez 2875 2 Ngao 1668 3 Nagayama 1610 4 Quick-To-See 1668 5 Ropeburn 1783 6 Urguhart 1380 7 Menchu 1438 8 Biri 1265 9 Catchpole 1495 10 Havel 1503 11 Magee 1610 12 Giljum 1714 13 Sedeghi 1742 14 Nguyen 1754 15 Dumas 1668 16 Maduro 1610 17 Smith 1081 18 Nozaki 1380 19 Patel 914 20 Newman 863 21 Markarian 978 22 Chang 920 23 Patel 914 24 Dancs 989 25 Schwartz 1265

25 rows selected.

Page 24: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

5. Display the employee last name and title in parentheses for all employees. Thereport should look like the output below.

SQL> SELECT last_name||’(’||INITCAP(title)||’)’2 EMPLOYEE3 FROM s_emp4 ORDER BY last_name;

EMPLOYEE----------------------------------------------------Biri(Warehouse Manager)Catchpole(Warehouse Manager)Chang(Stock Clerk)Dancs(Stock Clerk)Dumas(Sales Representative)Giljum(Sales Representative)Havel(Warehouse Manager)Maduro(Stock Clerk)Magee(Sales Representative)Markarian(Stock Clerk)Menchu(Warehouse Manager)Nagayama(Vp, Sales)Newman(Stock Clerk)Ngao(Vp, Operations)Nguyen(Sales Representative)Nozaki(Stock Clerk)Patel(Stock Clerk)Patel(Stock Clerk)Quick-To-See(Vp, Finance)Ropeburn(Vp, Administration)Schwartz(Stock Clerk)Sedeghi(Sales Representative)Smith(Stock Clerk)Urguhart(Warehouse Manager)Velasquez(President)

25 rows selected.

Page 25: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

6. Display each employee’s last name, hire date, and salary review date, which is thefirst Monday after six months of service. Format the dates to appear in the formatsimilar to Eighth of May 1992.

� Results have been formatted.

SQL> SELECT last_name, start_date,2 TO_CHAR(NEXT_DAY(ADD_MONTHS(start_date,6),3 ’MONDAY’),4 ’fmDdspth ”of” Month YYYY’) REVIEW5 FROM s_emp;

Continued

Page 26: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

6.—continued

LAST_NAME START_DAT REVIEW------------ --------- ------------------------------Velasquez 03-MAR-90 Tenth of September 1990Ngao 08-MAR-90 Tenth of September 1990Nagayama 17-JUN-91 Twenty-Third of December 1991Quick-To-See 07-APR-90 Eighth of October 1990Ropeburn 04-MAR-90 Tenth of September 1990Urguhart 18-JAN-91 Twenty-Second of July 1991Menchu 14-MAY-90 Nineteenth of November 1990Biri 07-APR-90 Eighth of October 1990Catchpole 09-FEB-92 Tenth of August 1992Havel 27-FEB-91 Second of September 1991Magee 14-MAY-90 Nineteenth of November 1990Giljum 18-JAN-92 Twentieth of July 1992Sedeghi 18-FEB-91 Nineteenth of August 1991Nguyen 22-JAN-92 Twenty-Seventh of July 1992Dumas 09-OCT-91 Thirteenth of April 1992Maduro 07-FEB-92 Tenth of August 1992Smith 08-MAR-90 Tenth of September 1990Nozaki 09-FEB-91 Twelfth of August 1991Patel 06-AUG-91 Tenth of February 1992Newman 21-JUL-91 Twenty-Seventh of January 1992Markarian 26-MAY-91 Second of December 1991Chang 30-NOV-90 Third of June 1991Patel 17-OCT-90 Twenty-Second of April 1991Dancs 17-MAR-91 Twenty-Third of September 1991Schwartz 09-MAY-91 Eleventh of November 1991

25 rows selected.

Page 27: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

7. Display the product name for products that have “ski” in the name.

SQL> SELECT name2 FROM s_product3 WHERE LOWER(name) LIKE ’%ski%’;

NAME--------------------Ace Ski BootPro Ski BootBunny Ski PoleAce Ski PolePro Ski Pole

8. For each employee, calculate the number of months between today and the datethe employee was hired. Order your result by the number of months employed.Round the number of months up to the closest whole number.

SQL> SELECT last_name,2 ROUND(MONTHS_BETWEEN(SYSDATE, start_date))3 MONTHS_WORKED4 FROM s_emp5 ORDER BY MONTHS_BETWEEN(SYSDATE, start_date);

Continued

Page 28: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

�������� � ����� ���������

8.—continued

LAST_NAME MONTHS_WORKED------------ -------------Catchpole 46Maduro 46Nguyen 47Giljum 47Dumas 50Patel 52Newman 53Nagayama 54Markarian 55Schwartz 55Dancs 57Havel 58Sedeghi 58Nozaki 58Urguhart 59Chang 61Patel 62Menchu 67Magee 67Quick-To-See 68Biri 68Ngao 69Smith 69Ropeburn 69Velasquez 69

25 rows selected.

Note: Your MONTHS_WORKED may differ from the solution because yourSYSDATE may return a different value.

Page 29: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!

�������� � ����� ���������

9. Display the last name for all employees and the day of the week they started.Order the results by the day of the week starting with Monday.

� Results have been formatted.

SQL> SELECT last_name, start_date,2 TO_CHAR(start_date, ’DAY’) DAY3 FROM s_emp4 ORDER BY TO_CHAR(start_date-1, ’d’);

LAST_NAME START_DAT DAY------------ --------- ----------Nagayama 17-JUN-91 MONDAYMenchu 14-MAY-90 MONDAYSedeghi 18-FEB-91 MONDAYMagee 14-MAY-90 MONDAYPatel 06-AUG-91 TUESDAYHavel 27-FEB-91 WEDNESDAYPatel 17-OCT-90 WEDNESDAYNguyen 22-JAN-92 WEDNESDAYDumas 09-OCT-91 WEDNESDAYNgao 08-MAR-90 THURSDAYSmith 08-MAR-90 THURSDAYSchwartz 09-MAY-91 THURSDAYUrguhart 18-JAN-91 FRIDAYChang 30-NOV-90 FRIDAYMaduro 07-FEB-92 FRIDAYVelasquez 03-MAR-90 SATURDAYQuick-To-See 07-APR-90 SATURDAYBiri 07-APR-90 SATURDAYNozaki 09-FEB-91 SATURDAYGiljum 18-JAN-92 SATURDAYRopeburn 04-MAR-90 SUNDAYNewman 21-JUL-91 SUNDAYDancs 17-MAR-91 SUNDAYMarkarian 26-MAY-91 SUNDAYCatchpole 09-FEB-92 SUNDAY

25 rows selected.

Page 30: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"

�������� � ����� ���������

10. Write a query that produces the following for each employee:

<employee name> earns <salary> monthly but wants<3 times salary>.

For example: ALLEN earns $1,100 monthly but wants $3,300.

SQL> SELECT UPPER(last_name)|| ’ earns ’ ||2 TO_CHAR(salary, ’fm$99,999’) 3 || ’ monthly but wants ’||4 TO_CHAR(salary*3, ’fm$99,999’) 5 ||’.’ ”Dream Salaries”6 FROM s_emp;

Dream Salaries---------------------------------------------------VELASQUEZ earns $2,500 monthly but wants $7,500.NGAO earns $1,450 monthly but wants $4,350.NAGAYAMA earns $1400 monthly but wants $4,200.QUICK-TO-SEE earns $,1450 monthly but wants $4,350.ROPEBURN earns $1,550 monthly but wants $4,650.URGUHART earns $1,200 monthly but wants $3,600.MENCHU earns $1,250 monthly but wants $3,750.BIRI earns $1,100 monthly but wants $3,300.CATCHPOLE earns $1,300 monthly but wants $3,900.HAVEL earns $1,307 monthly but wants $3,921.MAGEE earns $1,400 monthly but wants $4,200.GILJUM earns $1,490 monthly but wants $4,470.SEDEGHI earns $1,515 monthly but wants $4,545.NGUYEN earns $1,525 monthly but wants $4,575.DUMAS earns $1,450 monthly but wants $4,350.MADURO earns $1,400 monthly but wants $4,200.NOZAKI earns $1,200 monthly but wants $3,600.MARKARIAN earns $850 monthly but wants $2,550.PATEL earns $795 monthly but wants $2,385.SMITH earns $1,000 monthly but wants $3,000.PATEL earns $795 monthly but wants $2,385.NEWMAN earns $750 monthly but wants $2,250.CHANG earns $800 monthly but wants $2,400.DANCS earns $860 monthly but wants $2,580.SCHWARTZ earns $1,100 monthly but wants $3,300.

Page 31: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#

�������� � �����

Use the S_EMP, S_DEPT, S_CUSTOMER, S_REGION, S_ORD, S_ITEM, andS_PRODUCT tables to complete the following exercises.

1. Write a report containing each employee’s last name, department number, andname of their department.

SQL> SELECT s_emp.last_name, s_emp.dept_id,2 s_dept.name3 FROM s_emp, s_dept4 WHERE s_emp.dept_id = s_dept.id;

Continued

Page 32: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$

�������� � ����� ���������

1.—continued

LAST_NAME DEPT_ID NAME------------ ------- --------------------Velasquez 50 AdministrationNgao 41 OperationsNagayama 31 SalesQuick-To-See 10 FinanceRopeburn 50 AdministrationUrguhart 41 OperationsMenchu 42 OperationsBiri 43 OperationsCatchpole 44 OperationsHavel 45 OperationsMagee 31 SalesGiljum 32 SalesSedeghi 33 SalesNguyen 34 SalesDumas 35 SalesMaduro 41 OperationsSmith 41 OperationsNozaki 42 OperationsPatel 42 OperationsNewman 43 OperationsMarkarian 43 OperationsChang 44 OperationsPatel 34 SalesDancs 45 OperationsSchwartz 45 Operations

25 rows selected.

Page 33: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

2. Write a query to display the last name, department name, and region name of allemployees who earn a commission.

� Results have been formatted.

SQL> SELECT e.last_name, d.name, r.name2 FROM s_emp e, s_dept d, s_region r3 WHERE e.dept_id = d.id4 AND r.id = d.region_id5 AND e.commission_pct IS NOT NULL;

LAST_NAME NAME NAME------------ -------------- --------------------Magee Sales North AmericaGiljum Sales South AmericaSedeghi Sales Africa / Middle EastNguyen Sales AsiaDumas Sales Europe

3. Display the employee name and department name for Smith.

SQL> SELECT s_emp.last_name, s_dept.name2 FROM s_emp, s_dept3 WHERE s_emp.dept_id = s_dept.id4 AND s_emp.last_name = ’Smith’;

LAST_NAME NAME------------ ----------------------Smith Operations

Page 34: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

4. Display the product name, product number, and quantity ordered of all items inorder number 101. Label the quantity column ORDERED.

SQL> SELECT s_product.name, 2 s_product.id, 3 s_item.quantity ”ORDERED”4 FROM s_product, s_item5 WHERE s_product.id = s_item.product_id6 AND s_item.ord_id = 101;

NAME ID ORDERED--------------------------------- ----- -------Grand Prix Bicycle Tires 30421 15Pro Curling Bar 40422 30Prostar 10 Pound Weight 41010 20Prostar 100 Pound Weight 41100 35Major League Baseball 50169 40Griffey Glove 50417 27Cabrera Bat 50530 50

7 rows selected.

5. Display the customer number and the last name of their sales representative.Order the list by last name.

SQL> SELECT s_customer.id, s_emp.last_name2 FROM s_emp, s_customer3 WHERE s_emp.id = s_customer.sales_rep_id4 ORDER BY s_emp.last_name;

Continued

Page 35: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

5.—continued

ID LAST_NAME----- --------------- 205 Dumas 206 Dumas 208 Dumas 211 Dumas 215 Dumas 201 Giljum 210 Giljum 204 Magee 214 Magee 209 Magee 213 Magee 202 Nguyen 203 Nguyen 212 Sedeghi

14 rows selected.

6. Display the customer number, customer name, and order number of all customersand their orders. Display the customer number and name, even if they have notplaced an order.

SQL> SELECT s_customer.id ”Customer ID”,2 s_customer.name ”Customer Name”,3 s_ord.id ”Order ID”4 FROM s_customer, s_ord5 WHERE s_customer.id = 6 s_ord.customer_id (+);

Continued

Page 36: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

6.—continued

Customer ID Customer Name Order ID----------- ------------------------------ ---------- 201 Unisports 97 202 Simms Atheletics 98 203 Delhi Sports 99 204 Womansport 100 204 Womansport 111 205 Kam’s Sporting Goods 101 206 Sportique 102 207 Sweet Rock Sports 208 Muench Sports 103 208 Muench Sports 104 209 Beisbol Si! 105 210 Futbol Sonora 106 210 Futbol Sonora 112 211 Kuhn’s Sports 107 212 Hamada Sport 108 213 Big John’s Sports Emporium 109 214 Ojibway Retail 110 215 Sporta Russia

18 rows selected.

7. Display all employees by last name name and employee number along with theirmanager’s last name and manager number.

SQL> SELECT w.last_name EMP_NAME, w.id EMP_ID, 2 m.last_name MGR_NAME, m.id MGR_ID3 FROM s_emp w, s_emp m4 WHERE w.manager_id = m.id;

Continued

Page 37: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

7.—continued

EMP_NAME EMP_ID MGR_NAME MGR_ID------------ ---------- ------------ ----------Ngao 2 Velasquez 1Nagayama 3 Velasquez 1Quick-To-See 4 Velasquez 1Ropeburn 5 Velasquez 1Urguhart 6 Ngao 2Menchu 7 Ngao 2Biri 8 Ngao 2Catchpole 9 Ngao 2Havel 10 Ngao 2Magee 11 Nagayama 3Giljum 12 Nagayama 3Sedeghi 13 Nagayama 3Nguyen 14 Nagayama 3Dumas 15 Nagayama 3Maduro 16 Urguhart 6Smith 17 Urguhart 6Nozaki 18 Menchu 7Patel 19 Menchu 7Newman 20 Biri 8Markarian 21 Biri 8Chang 22 Catchpole 9Patel 23 Catchpole 9Dancs 24 Havel 10Schwartz 25 Havel 10

24 rows selected.

Page 38: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

�������� � ����� ���������

8. Modify the solution to exercise 7 to also display Velasquez, who has no manager.

SQL> SELECT w.last_name ”Employee Name”, w.id ”Employee ID”,

2 m.last_name ”Manager Name”, m.id ”Manager ID”

3 FROM s_emp w, s_emp m4 WHERE w.manager_id = m.id (+);

Employee Name Employee ID Manager Name Manager ID--------------- ----------- --------------- ----------Velasquez 1 Ngao 2 Velasquez 1Nagayama 3 Velasquez 1Quick-To-See 4 Velasquez 1Ropeburn 5 Velasquez 1Urguhart 6 Ngao 2Menchu 7 Ngao 2Biri 8 Ngao 2Catchpole 9 Ngao 2Havel 10 Ngao 2Magee 11 Nagayama 3Giljum 12 Nagayama 3Sedeghi 13 Nagayama 3Nguyen 14 Nagayama 3Dumas 15 Nagayama 3Maduro 16 Urguhart 6Nozaki 18 Menchu 7Markarian 21 Biri 8Patel 23 Catchpole 9Smith 17 Urguhart 6Patel 19 Menchu 7Newman 20 Biri 8Chang 22 Catchpole 9Dancs 24 Havel 10Schwartz 25 Havel 10

25 rows selected.

Page 39: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!

�������� � ����� ���������

9. Display all customers and the product number and quantities they ordered forthose customers whose order totaled more than 100,000.

SQL> SELECT c.name CUSTOMER, p.id PRODUCT_ID,2 i.quantity3 FROM s_customer c, s_product p, s_item i,4 s_ord o5 WHERE c.id = o.customer_id6 AND o.id = i.ord_id7 AND i.product_id = p.id8 AND o.total > 100000;

Continued

Page 40: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"

�������� � ����� ���������

9.—continued

CUSTOMER PRODUCT_ID QUANTITY------------------------------ ---------- ----------Womansport 10011 500Womansport 10013 400Womansport 10021 500Womansport 30326 600Womansport 41010 250Womansport 30433 450Womansport 10023 400Kuhn’s Sports 20106 50Kuhn’s Sports 20201 130Kuhn’s Sports 30421 55Kuhn’s Sports 30321 75Kuhn’s Sports 20108 22Hamada Sport 20510 9Hamada Sport 41080 50Hamada Sport 41100 42Hamada Sport 32861 57Hamada Sport 20512 18Hamada Sport 32779 60Hamada Sport 30321 85Big John’s Sports Emporium 10011 150Big John’s Sports Emporium 30426 500Big John’s Sports Emporium 50418 43Big John’s Sports Emporium 32861 50Big John’s Sports Emporium 30326 1500Big John’s Sports Emporium 10012 600Big John’s Sports Emporium 10022 300

26 rows selected.

Page 41: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#

�������� � �����

1. Determine the validity of the following statements. Circle either True or False.

a. Group functions work across many rows to produce one result.

� True

b. Group functions include nulls in calculations.

� False Group functions ignore null values. If you want to include null values,use the NVL function.

c. Use the HAVING clause to exclude rows from a group calculation.

� False The WHERE clause restricts rows prior to inclusion in a groupcalculation.

d. Use the HAVING clause to exclude groups of rows from the display.

� True

2. Display the highest and lowest order totals in the S_ORD. Label the columnsHighest and Lowest, respectively.

SQL> SELECT MAX (total) ”Highest”, 2 MIN (total) ”Lowest”3 FROM s_ord;

Highest Lowest---------- ---------- 1020935 377

3. Write a query to display the minimum and maximum salary for each job typeordered alphabetically.

SQL> SELECT title JOB, MAX(salary) MAXIMUM,2 MIN(salary) MINIMUM3 FROM s_emp4 GROUP BY title;

Continued

Page 42: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$

�������� � ����� ���������

3.—continued

JOB MAXIMUM MINIMUM------------------------- ---------- ----------President 2500 2500Sales Representative 1525 1400Stock Clerk 1400 750VP, Administration 1550 1550VP, Finance 1450 1450VP, Operations 1450 1450VP, Sales 1400 1400Warehouse Manager 1307 1100

8 rows selected.

4. Determine the number of managers without listing them.

SQL> SELECT COUNT(DISTINCT(manager_id))2 ”Number of Managers”3 FROM s_emp;

Number of Managers------------------ 8

5. Display the number of line items in each order under each order number, labeledNumber of Items.

SQL> SELECT ord_id, COUNT(*) ”NUMBER OF ITEMS”2 FROM s_item3 GROUP BY ord_id;

Continued

Page 43: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

5.—continued

ORD_ID NUMBER OF ITEMS---------- --------------- 97 2 98 1 99 4 100 7 101 7 102 2 103 2 104 4 105 3 106 6 107 5 108 7 109 7 110 2 111 2 112 1

16 rows selected.

6. Display the manager number and the salary of the lowest paid employee for thatmanager. Exclude any groups where the minimum salary is less than 1000. Sortthe output by salary.

SQL> SELECT manager_id,2 MIN(salary) ”LOWEST PAID EMPLOYEE”3 FROM s_emp4 GROUP BY manager_id5 HAVING MIN(salary) >= 10006 ORDER BY 2;

Continued

Page 44: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

6.—continued

MANAGER_ID LOWEST PAID EMPLOYEE---------- -------------------- 2 1100 1 1400 3 1400 2500

7. What is the difference between the highest and lowest salaries?

SQL> SELECT MAX(salary) - MIN (salary) DIFFERENCE2 FROM s_emp;

DIFFERENCE---------- 1750

Page 45: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

If you have time, complete the following exercises.

8. Display the product number and number of times it was ordered, labeled TimesOrdered. Only show those products that have been ordered at least three times.Order the data by the number of products ordered.

SQL> SELECT product_id, 2 COUNT(ord_id) ”TIMES ORDERED”3 FROM s_item4 GROUP BY product_id5 HAVING COUNT(ord_id) >= 36 ORDER BY COUNT(ord_id);

PRODUCT_ID TIMES ORDERED---------- --------------

20106 320108 320201 320510 350273 330421 320512 330321 4

8 rows selected.

9. Retrieve the region number, region name, and the number of departments withineach region.

SQL> SELECT r.id, r.name, COUNT(d.id) ”# OF DEPT”2 FROM s_dept d, s_region r3 WHERE d.region_id = r.id4 GROUP BY r.id, r.name;

Continued

Page 46: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� � ����� ���������

9.—continued

ID NAME # OF DEPT----- --------------------------- ----------------

1 North America 42 South America 23 Africa / Middle East 24 Asia 25 Europe 2

10. Display the order number and total item count for each order of 100 or moreitems. For example, if order number 99 contains quantity 30 of one item, andquantity 75 of another item, then the total item count for that order is 105.

SQL> SELECT ord_id, 2 SUM(quantity) ”TOTAL ITEM COUNT”3 FROM s_item4 GROUP BY ord_id5 HAVING SUM(quantity) >= 100;

ORD_ID TOTAL ITEM COUNT---------- -----------------

97 105099 165100 3100101 217102 145106 392107 332108 321109 3143

9 rows selected.

Page 47: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� � ����� ���������

11. Display the customer name and the number of orders for each customer.

SQL> SELECT c.name, COUNT(o.id) ”NUMBER OF ORDERS”2 FROM s_customer c, s_ord o3 WHERE c.id = o.customer_id4 GROUP BY c.name;

NAME NUMBER OF ORDERS-------------------------------- -----------------Beisbol Si! 1Big John’s Sports Emporium 1Delhi Sports 1Futbol Sonora 2Hamada Sport 1Kam’s Sporting Goods 1Kuhn’s Sports 1Muench Sports 2Simms Athletics 1Ojibway Retail 1Sportique 1Unisports 1Womansport 2

13 rows selected.

Page 48: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

�������� �����

1. Answer the following questions

a. Which query runs first with a subquery?

� Inner query runs first.

b. How many times does the first query run?

� The first query executes once.

c. You cannot use the equals (=) operator if the inner query returns more thanone value.

� True

i. If the answer is True, why and what operator should be used?

� The equals operator expects one value in return. Use the IN operator.

ii. If the answer is False, why?

2. Display the first name, last name, and start date for all employees in the samedepartment as Magee.

SQL> SELECT first_name, last_name, start_date2 FROM s_emp3 WHERE dept_id =4 (SELECT dept_id5 FROM s_emp6 WHERE last_name = ’Magee’);

FIRST_NAME LAST_NAME START_DAT-------------------- -------------------- ---------Midori Nagayama 17-JUN-91Colin Magee 14-MAY-90

Page 49: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!

�������� ����� ���������

3. Display the employee number, first name, last name, and user name for allemployees with salaries above the average salary.

SQL> SELECT id, first_name, last_name, userid2 FROM s_emp3 WHERE salary >4 (SELECT AVG(salary)5 FROM s_emp);

ID FIRST_NAME LAST_NAME USERID------- --------------- --------------- -------- 1 Carmen Velasquez cvelasqu 2 LaDoris Ngao lngao 3 Midori Nagayama mnagayam 4 Mark Quick-To-See mquickto 5 Audry Ropeburn aropebur 9 Antoinette Catchpole acatchpo 10 Marta Havel mhavel 11 Colin Magee cmagee 12 Henry Giljum hgiljum 13 Yasmin Sedeghi ysedeghi 14 Mai Nguyen mnguyen 15 Andre Dumas adumas 16 Elena Maduro emaduro

13 rows selected.

Page 50: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"

�������� ����� ���������

4. Display last name, department number, and title for all employees assigned toregion 1 or region 2.

SQL> SELECT last_name, dept_id, title2 FROM s_emp3 WHERE dept_id IN4 (SELECT id5 FROM s_dept6 WHERE region_id IN (1,2));

LAST_NAME DEPT_ID TITLE-------------------- --------- -------------------Velasquez 50 PresidentNgao 41 VP, OperationsNagayama 31 VP, SalesQuick-To-See 10 VP, FinanceRopeburn 50 VP, AdministrationUrguhart 41 Warehouse ManagerMenchu 42 Warehouse ManagerMagee 31 Sales RepresentativeGiljum 32 Sales RepresentativeMaduro 41 Stock ClerkSmith 41 Stock ClerkNozaki 42 Stock ClerkPatel 42 Stock Clerk

13 rows selected.

Page 51: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#

�������� ����� ���������

5. Display the last name and salary for all employees that report to LaDoris Ngao.

SQL> SELECT last_name, salary2 FROM s_emp3 WHERE manager_id =4 (SELECT id5 FROM s_emp6 WHERE last_name = ’Ngao’);

LAST_NAME SALARY------------------------- ---------Urguhart 1200Menchu 1250Biri 1100Catchpole 1300Havel 1307

Page 52: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$

�������� ����� ���������

6. Display the employee number, first name, and last name for all employees with asalary above the average salary and that work with any employee with a last namethat contains a “t”.

SQL> SELECT id, first_name, last_name2 FROM s_emp3 WHERE salary >4 (SELECT AVG(salary)5 FROM s_emp)6 AND dept_id IN7 (SELECT dept_id8 FROM s_emp9 WHERE UPPER(last_name) LIKE ’%T%’);

ID FIRST_NAME LAST_NAME------- -------------------- ------------------- 4 Mark Quick-To-See 14 Mai Nguyen 2 LaDoris Ngao 16 Elena Maduro 9 Antoinette Catchpole 10 Marta Havel

6 rows selected.

Page 53: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� ����� ���������

7. Display the customer number, customer name, customer rating, and salesrepresentative’s last name for all customers who are located in the North Americaregion or have Nguyen as their sales representative.

SQL> SELECT c.id, c.name, c.credit_rating, 2 e.last_name3 FROM s_customer c, s_emp e4 WHERE c.sales_rep_id = e.id5 AND (c.region_id = (select id from6 s_region7 where name = ‘North America’)8 OR c.sales_rep_id = (select id from s_emp9 where last_name =10 ‘Nguyen’));

ID NAME CREDIT_RA LAST_NAME––– –––––––––––––––––––––––––––– ––––––––– –––––––––202 Simms Athletics POOR Nguyen203 Delhi Sports GOOD Nguyen204 Womansport EXCELLENT Magee209 Beisbol Si! EXCELLENT Magee213 Big John’s Sports Emporium EXCELLENT Magee214 Ojibway Retail POOR Magee

6 rows selected.

Page 54: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� ����� ���������

8. Display the name and short description for any product that did not appear on anorder in the month of September, 1992.

� Results have been formatted.

SQL> SELECT name, short_desc DESCRIPTION2 FROM s_product3 WHERE id NOT IN4 (SELECT s_item.product_id5 FROM s_item, s_ord6 WHERE s_item.ord_id = s_ord.id7 AND s_ord.date_ordered BETWEEN8 ’01-SEP-92’ AND ’30-SEP-92’);

NAME DESCRIPTION------------------------ -------------------------Pro Ski Boot Advanced ski bootBunny Ski Pole Beginner’s ski polePro Ski Pole Advanced ski polePro Curling Bar Curling barProstar 10 Pound Weight Ten pound weightProstar 20 Pound Weight Twenty pound weightProstar 50 Pound Weight Fifty pound weightGriffey Glove Outfielder’s gloveCabrera Bat Thirty inch bat

9 rows selected.

Page 55: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� ����� ���������

9. Display the customer name and credit rating for all customers of salesrepresentative Andre Dumas.

SQL> SELECT name, credit_rating2 FROM s_customer3 WHERE sales_rep_id =4 (SELECT id5 FROM s_emp6 WHERE last_name = ’Dumas’);

NAME CREDIT_RA------------------------ ---------Kam’s Sporting Goods EXCELLENT Sportique EXCELLENTMuench Sports GOODKuhn’s Sports EXCELLENTSporta Russia POOR

Page 56: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� ����� ���������

10. Display each sales representative’s last name in region 1 and region 2, theircustomers’ names and each customer’s total sales orders.

SQL> SELECT e.last_name, c.name, sum(o.total) “Order2 Total”3 FROM s_emp e, s_customer c, s_ord o4 WHERE e.id = c.sales_rep_id5 AND c.id = o.customer_id6 AND e.dept_id in (select id from s_dept 7 where region_id in (1,2))8 GROUP BY e.last_name, c.name;

LAST_NAME NAME ORDER TOTAL–––––––––––––– –––––––––––––––––––––––––– ––––––––––––Giljum Futbol Sonora 16184Giljum Unisports 84000Magee Beisbol Si! 2722.24Magee Big John’s Sports Emporium 1020935Magee Ojibway Retail 1539.13Magee Womansport 603870

6 rows selected.

Page 57: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����

�������� ! �����

Determine whether the following statements are true.

1. A single ampersand substitution variable prompts only once.

� TrueHowever, if the variable is defined, then the single ampersand substitutionvariable will not prompt at all. In fact, it will pick up the value in thepredefined variable.

2. The ACCEPT command is a SQL command.

� FalseThe ACCEPT command is a SQL*Plus command. It is issued at the SQLprompt.

Page 58: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

�������� ! ����� ���������

The following questions use the S_EMP, S_CUSTOMER, and S_PRODUCT tables.

3. Write a script file to display the user ID, first and last names concatenatedtogether, and start dates of employees within a specified range. Prompt the userfor the two ranges using the ACCEPT command. Use the format “MM/DD/YY”.Save the script file as p7q3.sql.

SET ECHO OFFSET VERIFY OFFACCEPT low_date DATE FORMAT ’MM/DD/YY’ -PROMPT ”Enter the low date range (’MM/DD/YY’): ”ACCEPT high_date DATE FORMAT ’MM/DD/YY’ -PROMPT ”Enter the high date range (’MM/DD/YY’): ”COLUMN employee FORMAT A30SELECT userid, first_name||’ ’||last_name employee,

start_dateFROM s_empWHERE start_date BETWEENTO_DATE(’&low_date’,’MM/DD/YY’)

AND TO_DATE(’&high_date’,’MM/DD/YY’)/UNDEFINE low_dateUNDEFINE high_dateCOLUMN employee CLEARSET VERIFY ONSET ECHO ON

SQL> START p7q3

SET ECHO OFFEnter the low date range (’MM/DD/YY’): 09/01/91Enter the high date range (’MM/DD/YY’): 09/01/92

USERID EMPLOYEE START_DAT-------- ------------------------------ ---------acatchpo Antoinette Catchpole 09-FEB-92hgiljum Henry Giljum 18-JAN-92mnguyen Mai Nguyen 22-JAN-92adumas Andre Dumas 09-OCT-91emaduro Elena Maduro 07-FEB-92

Page 59: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!

�������� ! ����� ���������

4. Write a script to search for customer names and numbers. The search conditionshould allow for case-insensitive name searches. Save the script file as p7q4.sql.Your result should look like the output below.

SET ECHO OFFACCEPT p_customer PROMPT ”Please enter the customer’s name: ”COLUMN name HEADING ”CUSTOMER NAME” FORMAT A40SELECT id, nameFROM s_customerWHERE UPPER(name) LIKE UPPER(’%&p_customer%’)/UNDEFINE p_customerCOLUMN name CLEARSET ECHO ON

� Notice that the variable is between single quotation marks. Without thequotation marks, the operator would have to input the quotation marks at theprompt.

SQL> START p7q4

SET ECHO OFFPlease enter the customer’s name: sport

ID CUSTOMER NAME------ ---------------------------------------- 201 Unisports 203 Delhi Sports 204 Womansport 205 Kam’s Sporting Goods 206 Sportique 207 Sweet Rock Sports 208 Muench Sports 211 Kuhn’s Sports 212 Hamada Sport 213 Big John’s Sports Emporium 215 Sporta Russia

11 rows selected.

Page 60: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"

�������� ! ����� ���������

5. Write a report containing the sales representative name, customer name, and eachcustomer’s total sales order. Prompt the user for a region number. Save the scriptas p7q5.sql.

SET ECHO OFFSET VERIFY OFFACCEPT p_region NUMBER PROMPT ’Please enter a region number: ’COLUMN employee FORMAT A25COLUMN customer FORMAT A30COLUMN sales FORMAT $9,999,999SELECT a.first_name||’ ’||a.last_name EMPLOYEE, b.name CUSTOMER, SUM(c.total) SALESFROM s_emp a, s_customer b, s_ord cWHERE a.id = b.sales_rep_idAND b.id = c.customer_idAND a.dept_id IN (SELECT id FROM s_dept WHERE region_id IN (&p_region))GROUP BY a.first_name||’ ’||a.last_name, b.name/COLUMN sales CLEARCOLUMN customer CLEARCOLUMN employee CLEARSET VERIFY ONSET ECHO ON

SQL> START p7q5

Please enter a region number: 1

EMPLOYEE CUSTOMER SALES---------------------- --------------------------- -----------Colin Magee Beisbol Si! $2,722Colin Magee Big John’s Sports Emporium $1,020,935Colin Magee Ojibway Retail $1,539Colin Magee Womansport $603,870

Note: SQL*Plus allows you to suppress duplicate values by using the BREAKcommand. More about the BREAK command is covered in Advanced SQLand SQL*Plus course.

Page 61: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#

�������� # �����

1. Are the following examples syntactically correct? If not, why?

a. Correct/Incorrect

� Incorrect.A comma is required after the NAME definition in line 3 for a tableconstraint.

SQL> CREATE TABLE T_30002 (id NUMBER(7),3 name VARCHAR2(25)4 CONSTRAINT table_id_pk PRIMARY KEY(id));

b. Correct/Incorrect

� Incorrect.Remove the comma in line 3 to include the NOT NULL columnconstraint.Add “(id)” after “PRIMARY KEY” in line 9 because this is a tableconstraint.Change table name in line 1 because 1995_orders is an illegal tablename. A table name must begin with a letter.

SQL> CREATE TABLE 1995_orders2 (id NUMBER(7),3 customer_id NUMBER(7),4 CONSTRAINT ord_cust_id_nn NOT NULL,5 total NUMBER(11,2),6 filled CHAR(1)7 CONSTRAINT ord_filled_ck CHECK 8 (filled IN (’Y’,’N’)),9 CONSTRAINT ord_id_pk PRIMARY KEY);

Page 62: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �������� $

�������� # ����� ���������

2. Create the DEPARTMENT table based on the table instance chart given below.Enter the syntax in a script named p9q2.sql, then execute the script to create thetable. Confirm that the table is created. You will add data to the table in anotherlesson.

Table name: DEPARTMENT

Column Name ID NAME

Key Type PK

Nulls/ Unique NN, U

FK Table

FK Column

Datatype NUMBER CHAR

Length 7 25

� Script p9q2.sql contents.

SET ECHO OFFCREATE TABLE department(id NUMBER(7) CONSTRAINT department_id_pk PRIMARY KEY, name VARCHAR2(25))/SET ECHO ON

SQL> START p9q2

Table created.

SQL> DESCRIBE department

Name Null? Type -------------------------- -------- ---- ID NOT NULL NUMBER(7) NAME VARCHAR2(25)

Page 63: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �� �

�������� # ����� ���������

3. Create the EMPLOYEE table based on the table instance chart given below. Enterthe syntax in a script p9q3.sql, then execute the script to create the table. Confirmthat the table is created. You will add data to the table in another lesson.

Table name: EMPLOYEE

ColumnName

ID LAST_NAME FIRST_NAME DEPT_ID

Key Type PK FK

Nulls/ Unique NN, U NN NN

FK Table DEPARTMENT

FK Column ID

Datatype NUMBER CHAR CHAR NUMBER

Length 7 25 25 7

Continued

Page 64: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �������� �

�������� # ����� ���������

3.—continued

� Script p9q3.sql contents.

SET ECHO OFFCREATE TABLE employee(id NUMBER(7) CONSTRAINT employee_id_pk PRIMARY KEY, last_name VARCHAR2(25) CONSTRAINT employee_last_name_nn NOT NULL, first_name VARCHAR2(25), dept_id NUMBER (7) CONSTRAINT employee_dept_id_nn NOT NULL CONSTRAINT employee_dept_id_fk REFERENCES department(id))/SET ECHO ON

SQL> START p9q3

Table created.

SQL> DESCRIBE employee

Name Null? Type––––––––––––––––––––––– ––––––––– –––––––––––ID NOT NULL NUMBER(7)LAST_NAME NOT NULL VARCHAR2(25)FIRST_NAME VARCHAR2(25)DEPT_ID NOT NULL NUMBER(7)

Page 65: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �� �

�������� �$ �����

1. Select all the views from the data dictionary pertaining to Table. You can adjustthe column formats by using the SQL*Plus COLUMN command.

SQL> COLUMN TABLE_NAME FORMAT A22SQL> COLUMN COMMENTS FORMAT A50 WORD_WRAPPEDSQL> SELECT *2 FROM DICTIONARY3 WHERE LOWER(COMMENTS) LIKE ’%table%’;

TABLE_NAME COMMENTS----------------- --------------------------------ALL_CATALOG All tables, views, synonyms, sequences accessible to the userALL_COL_COMMENTS Comments on columns of accessible tables and viewsALL_CONSTRAINTS Constraint definitions on accessible tablesALL_INDEXES Descriptions of indexes on tables accessible to the userALL_IND_COLUMNS COLUMNs comprising INDEXes on accessible TABLESALL_TABLES Description of tables accessible to the userALL_TAB_COLUMNS Columns of all tables, views and clustersALL_TAB_COMMENTS Comments on tables and views accessible to the userALL_TRIGGER_COLS Column usage in user’s triggers or in triggers on user’s tablesUSER_AUDIT_OBJECT Audit trail records for statements concerning objects, specifically: table, cluster, view, index, sequence, [public] database link, [public] synonym, procedure, trigger, rollback segment, tablespace, role, user

Page 66: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �������� �

�������� �$ ����� ���������

1.—continued

TABLE_NAME COMMENTS----------------- --------------------------------USER_CATALOG Tables, Views, Synonyms and Sequences owned by the userUSER_CLU_COLUMNS Mapping of table columns to cluster columnsUSER_COL_COMMENTS Comments on columns of user’s tables and viewsUSER_CONSTRAINTS Constraint definitions on user’s own tablesUSER_FREE_SPACE Free extents in tablespaces accessible to the userUSER_IND_COLUMNS COLUMNs comprising user’s INDEXes or on user’s TABLESUSER_OBJ_AUDIT_OP Auditing options for user’s ownTS tables and viewsUSER_TABLES Description of the user’s own tablesUSER_TABLESPACES Description of accessible tablespacesUSER_TAB_COLUMNS Columns of user’s tables, views and clustersUSER_TAB_COMMENTS Comments on the tables and views owned by the userUSER_TS_QUOTAS Tablespace quotas for the userAUDIT_ACTIONS Description table for audit trail action type codes. Maps action type numbers to action type namesDICTIONARY Description of data dictionary tables and viewsDICT_COLUMNS Description of columns in data dictionary tables and viewsROLE_TAB_PRIVS Table privileges granted to rolesTABS Synonym for USER_TABLES27 rows selected.

Page 67: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �� �

�������� �$ ����� ���������

2. If a query is very lengthy, what SQL*Plus command can you set before youexecute the query to show only one page at a time?

� Issue the SQL*Plus command SET PAUSE ON.

3. Query the USER_OBJECTS data dictionary to see information about the tablesyou created in Practice 9, DEPARTMENT and EMPLOYEE tables.

SQL> SELECT *2 FROM user_objects3 WHERE object_type = ’TABLE’4 AND object_name5 IN (’EMPLOYEE’,’DEPARTMENT’);

OBJECT_NAM OBJECT_ID OBJECT_TYPE CREATED---------- ---------- ------------- ---------LAST_DDL_ TIMESTAMP STATUS--------- -------------------- -------DEPARTMENT 94460 TABLE 10-FEB-9610-FEB-96 1996-02-10:10:52:29 VALID

EMPLOYEE 94462 TABLE 10-FEB-9610-FEB-96 1996-02-10:10:52:30 VALID

Page 68: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������

�������� �$ ����� ���������

4. Create a script to execute a generic query to confirm the constraints for the tablesyou have created. You can use a substitution parameter for the table name. Savethe query as p10q4.sql. Execute the script to confirm the constraints for the tablesyou created in Practice 9, DEPARTMENT and EMPLOYEE tables.

� Script p10q4.sql contents.

SET ECHO OFFREM SQL*Plus commandsACCEPT table PROMPT ’Table to view constraints: ’COLUMN constraint_name FORMAT A25COLUMN search_condition FORMAT A25COLUMN r_constraint_name FORMAT A20

REM SELECT statement to query the constraintsSELECT constraint_name, constraint_type,

search_condition, r_constraint_nameFROM user_constraintsWHERE table_name = UPPER(’&table’)/CLEAR COLUMNSET ECHO ON

SQL> START p10q4

Table to view constraints: department

CONSTRAINT_NAME C------------------------- -SEARCH_CONDITION R_CONSTRAINT_NAME------------------------- --------------------DEPARTMENT_ID_PK P

Page 69: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �� !

�������� �$ ����� ���������

4.—continued

SQL> START p10q4

Table to view constraints: employee

CONSTRAINT_NAME C------------------------- -SEARCH_CONDITION R_CONSTRAINT_NAME------------------------- --------------------EMPLOYEE_LAST_NAME_NN CLAST_NAME IS NOT NULL

EMPLOYEE_ID_PK P

EMPLOYEE_DEPT_ID_FK R DEPARTMENT_ID_PKEMPLOYEE_DEPT_ID_NN CDEPT_ID IS NOT NULL

Page 70: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �������� "

�������� �� �����

1. Insert data into the DEPARTMENT and EMPLOYEE tables.

a. Describe the DEPARTMENT and EMPLOYEE tables to identify the columnnames.

SQL> DESCRIBE department

Name Null? Type-------------------------- -------- ----ID NOT NULL NUMBER(7)NAME VARCHAR2(25)

SQL> DESCRIBE employee

Name Null? Type-------------------------- -------- ----ID NOT NULL NUMBER(7)LAST_NAME NOT NULL VARCHAR2(25)FIRST_NAME VARCHAR2(25)DEPT_ID NOT NULL NUMBER(7)

b. View the constraints on each table to identify the primary key and any otherconstraints. Execute the script p10q4.sql, which is a generic query to confirmconstraints.

SQL> START p10q4

Table to view constraints: department

CONSTRAINT_NAME C------------------------- -SEARCH_CONDITION R_CONSTRAINT_NAME------------------------- --------------------DEPARTMENT_ID_PK P

Page 71: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �� #

�������� �� ����� ���������

1b.—continued

SQL> START p10q4

Table to view constraints: employee

CONSTRAINT_NAME C------------------------- -SEARCH_CONDITION R_CONSTRAINT_NAME------------------------- --------------------EMPLOYEE_LAST_NAME_NN CLAST_NAME IS NOT NULL

EMPLOYEE_ID_PK P

EMPLOYEE_DEPT_ID_FK R DEPARTMENT_ID_PK

c. Add a row of data to the DEPARTMENT table. The department number is 10and the department name is Finance. Do not list the columns in the INSERTclause.

SQL> INSERT INTO department2 VALUES (10, ’Finance’);

1 row created.

Page 72: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������!$

�������� �� ����� ���������

1.—continued

d. Add two rows of data to the EMPLOYEE table. Write a script namedp11q1d.sql that prompts you for each column value. The first employee isDonna Smith in department number 10, and her employee number is 200. Thesecond employee is Albert Jones in department number 54, and his employeenumber is 201. What was the result and why?

SET ECHO OFFINSERT INTO employee (first_name, last_name, dept_id, id)VALUES (’&first_name’, ’&last_name’, &department_number, &employee_number)/SET ECHO ON

SQL> START p11q1d

SQL> SET ECHO OFFEnter value for first_name: DonnaEnter value for last_name: SmithEnter value for department_number: 10Enter value for employee_number: 200

1 row created.

Page 73: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��!�

�������� �� ����� ���������

1d.—continued

SQL> START p11q1d

SQL> SET ECHO OFFEnter value for first_name: AlbertEnter value for last_name: JonesEnter value for department_number: 54Enter value for employee_number: 201INSERT INTO employee (first_name, *ERROR at line 1: ORA-02291: integrity constraint (PREP40.EMPLOYEE_DEPT_ID_FK) violated - parent key not found

� Integrity constraint error occurred because department number 54 doesnot exist.

e. Insert into the DEPARTMENT table department number 10 and departmentname of Marketing. What was the result and why?

SQL> INSERT INTO department2 VALUES (10, ’Marketing’);

INSERT INTO department *ERROR at line 1: ORA-00001: unique constraint (PREP40.DEPARTMENT_ID_PK) violated

� Unique constraint error occurred because a department number 10already exists.

Page 74: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������!�

�������� �� ����� ���������

1.—continued

f. Confirm your additions to the tables.

SQL> SELECT *2 FROM department;

ID NAME---------- ------------------------- 10 Finance

SQL> SELECT *2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID ---- ---------- ---------- -------- 200 Smith Donna 10

Page 75: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��!�

�������� �� ����� ���������

1.—continued

g. Write a script named p11q1g.sql to prompt the user to add the following rowsto the DEPARTMENT table: Marketing as number 37; Sales as number 54;and Personnel as number 75.

SET ECHO OFFINSERT INTO department (name, id)VALUES (’&department_name’,&id)/SET ECHO ON

SQL> START p11q1g

SQL> SET ECHO OFFEnter value for department_name: MarketingEnter value for id: 37

1 row created.

SQL> START p11q1g

SQL> SET ECHO OFFEnter value for department_name: SalesEnter value for id: 54

1 row created.

SQL> START p11q1g

SQL> SET ECHO OFFEnter value for department_name: PersonnelEnter value for id: 75

1 row created.

Page 76: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������!�

�������� �� ����� ���������

1.—continued

h. Execute the p11q1d.sql script to add the following rows to the EMPLOYEEtable: Albert Jones in department number 54, and employee number 201;Harry Chin in department 75 and employee number 202; Rey Guiliani indepartment 37 and employee number 203.

SQL> START p11q1d

SQL> SET ECHO OFFEnter value for first_name: AlbertEnter value for last_name: JonesEnter value for department_number: 54Enter value for employee_number: 201

1 row created.

SQL> START p11q1d

SQL> SET ECHO OFFEnter value for first_name: HarryEnter value for last_name: ChinEnter value for department_number: 75Enter value for employee_number: 202

1 row created.

SQL> START p11q1d

SQL> SET ECHO OFFEnter value for first_name: ReyEnter value for last_name: GuilianiEnter value for department_number: 37Enter value for employee_number: 203

1 row created.

Page 77: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��!�

�������� �� ����� ���������

1.—continued

i. Confirm your additions to the tables.

SQL> SELECT *2 FROM department;

ID NAME---- ------------------------- 10 Finance 37 Marketing 54 Sales 75 Personnel

SQL> SELECT *2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID---- ---------- ---------- -------- 200 Smith Donna 10 201 Jones Albert 54 202 Chin Harry 75 203 Guiliani Rey 37

j. Make the data additions permanent.

SQL> COMMIT;

Commit complete.

Page 78: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������!

�������� �� ����� ���������

2. Update and delete data in the DEPARTMENT and EMPLOYEE tables.

a. Change the name of the Personnel department to Human Resources.

SQL> UPDATE department2 SET name = ’Human Resources’3 WHERE id = 75;

1 row updated.

b. Change the last name of employee 202 to Korsgaard.

SQL> UPDATE employee2 SET last_name = ’Korsgaard’3 WHERE id = 202;

1 row updated.

c. Verify your changes to the tables.

SQL> SELECT *2 FROM department3 WHERE name = ’Human Resources’;

ID NAME---- ------------------------- 75 Human Resources

SQL> SELECT *2 FROM employee3 WHERE id = 202;

ID LAST_NAME FIRST_NAME DEPT_ID---- ---------- ---------- -------- 202 Korsgaard Harry 75

Page 79: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��!!

�������� �� ����� ���������

2.—continued

d. Attempt to delete department 54. What was the result and why?

SQL> DELETE FROM department2 WHERE id = 54;

DELETE FROM department *ERROR at line 1: ORA-02292: integrity constraint (PREP40.EMPLOYEE_DEPT_ID_FK) violated - child record found

� Integrity constraint violation because there is foreign key reference todepartment number 54 in the EMPLOYEE table.

e. Delete Albert Jones from the EMPLOYEE table.

SQL> SELECT *2 FROM employee3 WHERE last_name = ’Jones’;

ID LAST_NAME FIRST_NAME DEPT_ID---- ---------- ---------- -------- 201 Jones Albert 54

SQL> DELETE FROM employee2 WHERE id = 201;

1 row deleted.

Page 80: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������!"

�������� �� ����� ���������

2.—continued

f. Attempt to delete department 54 from the DEPARTMENT table again. Whatwas the result and why?

SQL> DELETE FROM department2 WHERE id = 54;

1 row deleted.

� The deletion is successful now because the foreign key reference todepartment number 54 was removed when the record for Albert Joneswas deleted.

g. Verify the changes to your tables.

SQL> SELECT *2 FROM department;

ID NAME---- ------------------------- 10 Finance 37 Marketing 75 Human Resources

SQL> SELECT *2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID---- ---------- ---------- -------- 200 Smith Donna 10 202 Korsgaard Harry 75 203 Guiliani Rey 37

Page 81: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��!#

�������� �� ����� ���������

2.—continued

h. Commit all pending changes.

SQL> COMMIT;

Commit complete.

3. Control data transactions to the DEPARTMENT and EMPLOYEE tables.

a. Execute the p11q1g.sql script to reinstate the Sales department as departmentnumber 54.

SQL> start p11q1g

SQL> SET ECHO OFFEnter value for department_name: SalesEnter value for id: 54

1 row created.

b. Verify your addition.

SQL> SELECT *2 FROM department3 WHERE id = 54;

ID NAME---- ------------------------- 54 Sales

c. Mark a transaction processing savepoint.

SQL> SAVEPOINT sales;

Page 82: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������"$

�������� �� ����� ���������

3.—continued

d. Empty the entire EMPLOYEE table.

SQL> DELETE FROM employee;

3 rows deleted.

e. Verify that the EMPLOYEE table is empty.

SQL> SELECT *2 FROM employee;

no rows selected

f. Discard the most recent DELETE operation without discarding the mostrecent INSERT operation.

SQL> ROLLBACK TO sales;

Rollback complete.

g. Verify that the new row in the DEPARTMENT table is still intact. Verify thatthe EMPLOYEE table has all three rows.

SQL> SELECT *2 FROM department;

ID NAME---- ------------------------- 10 Finance 37 Marketing 54 Sales 75 Human Resources

Page 83: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��"�

�������� �� ����� ���������

3g.—continued

SQL> SELECT *2 FROM employee;

ID LAST_NAME FIRST_NAME DEPT_ID---- ---------- ---------- -------- 200 Smith Donna 10 202 Korsgaard Harry 75 203 Guiliani Rey 37

h. Make the data addition permanent.

SQL> COMMIT;

Commit complete.

Page 84: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������"�

�������� �� �����

1. Create a WORKER table, which copies the data from the EMPLOYEE table.Describe the table to confirm its structure.

SQL> CREATE TABLE worker2 AS (SELECT *3 FROM employee);

Table created.

SQL> DESCRIBE worker

Name Null? Type-------------------------- -------- ----ID NUMBER(7)LAST_NAME NOT NULL VARCHAR2(25)FIRST_NAME VARCHAR2(25)DEPT_ID NOT NULL NUMBER(7)

2. View the constraints for this new table. Save this command to a script namedp12q2.sql. Note the types and names of the constraints.

SQL> SELECT constraint_name, constraint_type,2 search_condition, r_constraint_name3 FROM user_constraints4 WHERE table_name = ’WORKER’;

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAI--------------- - --------------------- ----------SYS_C00108545 C LAST_NAME IS NOT NULLSYS_C00108546 C DEPT_ID IS NOT NULL

SQL> SAVE p12q2

Created file p12q2

� Your constraint names may be different from those listed here because theyare system generated.

Page 85: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��"�

�������� �� ����� ���������

3. Compare these constraints to those in the EMPLOYEE table. Note the types andnames of the constraints.

SQL> SELECT constraint_name, constraint_type,2 search_condition, r_constraint_name3 FROM user_constraints4 WHERE table_name = ’EMPLOYEE’;

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAI--------------- - --------------------- ----------EMP_LAST_NN C LAST_NAME IS NOT NULLEMP_DEPT_ID_NN C DEPT_ID IS NOT NULLEMP_ID_PK PEMP_DEPT_ID_FK R DEPT_ID_PK

4. Add a table level PRIMARY KEY constraint to the WORKER table using the IDcolumn. The constraint should be immediately enabled.

SQL> ALTER TABLE worker2 ADD CONSTRAINT worker_id_pk PRIMARY KEY(id);

Table altered.

5. Add a foreign key reference from the DEPARTMENT table to theDEPTARTMENT_ID column in the WORKER table. Confirm that theconstraints were added by re-executing p12q2.sql.

SQL> ALTER TABLE worker2 ADD CONSTRAINT worker_dept_id_fk 3 FOREIGN KEY(dept_id) 4 REFERENCES department(id);

Table altered.

Page 86: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������"�

�������� �� ����� ���������

5.—continued

SQL> START p12q2

CONSTRAINT_NAME C SEARCH_CONDITION R_CONSTRAI--------------- - --------------------- ----------SYS_C00108545 C LAST_NAME IS NOT NULLSYS_C00108546 C DEPT_ID IS NOT NULLWORKER_ID_PK PWORKER_DEPT_ID_FK R DEPT_ID_PK

6. Display the object names and types from the USER_OBJECTS data dictionaryview. You may want to format the columns for readability. Notice that the newtable and a new index were created.

SQL> COLUMN object_name FORMAT A30

SQL> SELECT object_name, object_type2 FROM user_objects3 ORDER BY object_name;

OBJECT_NAME OBJECT_TYPE------------------------------ -------------DEPARTMENT TABLEDEPT_ID_PK INDEXEMPLOYEE TABLEEMP_ID_PK INDEXS_CUSTOMER TABLES_CUSTOMER_ID SEQUENCES_CUSTOMER_ID_PK INDEXS_DEPT TABLES_DEPT_ID SEQUENCE

Page 87: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��"�

�������� �� ����� ���������

6.—continued

S_DEPT_ID_PK INDEXS_DEPT_NAME_REGION_ID_UK INDEXS_EMP TABLES_EMP_ID SEQUENCES_EMP_ID_PK INDEXS_EMP_USERID_UK INDEXS_IMAGE TABLES_IMAGE_ID SEQUENCES_IMAGE_ID_PK INDEXS_INVENTORY TABLES_INVENTORY_PRODID_WARID_PK INDEXS_ITEM TABLES_ITEM_ORDID_ITEMID_PK INDEXS_ITEM_ORDID_PRODID_UK INDEXS_LONGTEXT TABLES_LONGTEXT_ID SEQUENCES_LONGTEXT_ID_PK INDEXS_ORD TABLES_ORD_ID SEQUENCES_ORD_ID_PK INDEXS_PRODUCT TABLES_PRODUCT_ID SEQUENCES_PRODUCT_ID_PK INDEXS_PRODUCT_NAME_UK INDEXS_REGION TABLES_REGION_ID SEQUENCES_REGION_ID_PK INDEXS_REGION_NAME_UK INDEXS_TITLE TABLES_TITLE_TITLE_PK INDEXS_WAREHOUSE TABLES_WAREHOUSE_ID SEQUENCES_WAREHOUSE_ID_PK INDEXWORKER TABLEWORKER_ID_PK INDEX

44 rows selected.

Page 88: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������"

�������� �� ����� ���������

7. Drop the EMPLOYEE table, while leaving the WORKER table in the database.

SQL> DROP TABLE employee;

Table dropped.

8. Modify the WORKER table. Add a TITLE column of VARCHAR2 datatype,length 30.

SQL> ALTER TABLE worker2 ADD (title VARCHAR2(30));

Table altered.

SQL> DESCRIBE worker

Name Null? Type-------------------------- -------- ----ID NOT NULL NUMBER(7)LAST_NAME NOT NULL VARCHAR2(25)FIRST_NAME VARCHAR2(25)DEPT_ID NOT NULL NUMBER(7)TITLE VARCHAR2(30)

Page 89: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��"!

�������� �� ����� ���������

9. Add a comment to the WORKER and DEPARTMENT table definitionsdescribing the tables. Confirm your additions in the data dictionary.

TABLE_NAME COMMENTS--------------- ------------------------------DEPARTMENT Departmental ListingWORKER Employee Information

SQL> COMMENT ON TABLE department2 IS ’Departmental Listings’;

Comment created.

SQL> COMMENT ON TABLE worker2 IS ’Employee Information’;

Comment created.

SQL> SELECT table_name, comments2 FROM user_tab_comments3 WHERE table_name IN4 (’WORKER’,’DEPARTMENT’);

TABLE_NAME COMMENTS--------------- ------------------------------DEPARTMENT Departmental ListingWORKER Employee Information

Page 90: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������""

�������� �� �����

1. Create a sequence to be used with the DEPARTMENT table’s primary keycolumn. The sequence should start at 76 and have a maximum value of 80. Besure that it increments by one. Name the sequence DEPT_ID_SEQ.

SQL> CREATE SEQUENCE dept_id_seq2 START WITH 763 MAXVALUE 804 NOCACHE5 NOCYCLE;

Sequence created.

2. Create another sequence. This sequence will be used with the WORKER table’sprimary key column. Start this sequence at 204, and set the maximum value to be9999999. Be sure that it increments by one. Allow the sequence to cache 5numbers. Name the sequence WORKER_ID_SEQ.

SQL> CREATE SEQUENCE worker_id_seq2 START WITH 2043 MAXVALUE 99999994 CACHE 55 NOCYCLE;

Sequence created.

Page 91: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��"#

�������� �� ����� ���������

3. Write a script to display the following information about your sequences:sequence name, cache size, maximum value, increment size, and last numbergenerated. Name the script p13q3.sql.

SET ECHO OFFCOLUMN sequence_name FORMAT A15SELECT sequence_name, cache_size, max_value,

increment_by, last_numberFROM user_sequencesWHERE sequence_name IN (’DEPT_ID_SEQ’,’WORKER_ID_SEQ’)/SET ECHO ON

SQL> START p13q3

SET ECHO OFF

SEQUENCE_NAME CACHE_SIZE MAX_VALUE INCREMENT_BY LAST_NUMBER--------------- ---------- ---------- ------------ -----------DEPT_ID_SEQ 0 80 1 76WORKER_ID_SEQ 5 9999999 1 204

4. Write an interactive script to insert a row into the DEPARTMENT table. Nameyour script p13q4.sql. Be sure to use the sequence you created for the ID column.Create a customized prompt to enter the department name. Execute your script.Add two departments named Education and Administration. Confirm youradditions.

SET ECHO OFFACCEPT name PROMPT ’Enter the department name: ’INSERT INTO department (id, name)VALUES (dept_id_seq.NEXTVAL, ’&name’)/SET ECHO ON

Page 92: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������#$

�������� �� ����� ���������

4.—continued

SQL> START p13q4

Enter the department name: Education

1 row created.

SQL> START p13q4

Enter the department name: Administration

1 row created.

SQL> SELECT *2 FROM department;

ID NAME––– -------------------------10 Finance37 Marketing76 Education75 Human Resources54 Sales77 Administration

Page 93: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��#�

�������� �� ����� ���������

5. Write a script to insert two rows into the WORKER table. Name your scriptp13q5.sql. Use the sequence you create for the ID column. Execute your script.Add Tomas Lira as the President in the last department you just added to thetable. The other employee is Anna Seigher who is the Vice President in theFinance department.

SET ECHO OFFINSERT INTO worker (first_name, last_name, dept_id, title, id)VALUES (’&first_name’, ’&last_name’, &department_number, ’&title’, worker_id_seq.NEXTVAL)/SET ECHO ON

SQL> START p13q5

SQL> SET ECHO OFFEnter value for first_name: TomasEnter value for last_name: LiraEnter value for department_number: 77Enter value for title: President

1 row created.

SQL> START p13q5

SQL> SET ECHO OFFEnter value for first_name: AnnaEnter value for last_name: SeiglerEnter value for department_number: 10Enter value for title: Vice President

1 row created.

Page 94: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������#�

�������� �� ����� ���������

6. Confirm your additions to the DEPARTMENT table and WORKER table. Notethe highest primary key values for each table.

SQL> SELECT *2 FROM department;

ID NAME---- ------------------------- 10 Finance 37 Marketing 76 Education 75 Human Resources 54 Sales 77 Administration

SQL> SELECT *2 FROM worker;

ID LAST_NAME FIRST_NAME DEPT_ID TITLE---- ---------- ---------- -------- --------------- 200 Smith Donna 10 204 Lira Tomas 77 President 202 Korsgaard Harry 75 203 Guiliani Rey 37 205 Seigler Anna 10 Vice President

Page 95: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��#�

�������� �� ����� ���������

7. Display information about your sequences by executing the p13q3.sql script.Notice that the WORKER_ID_SEQ last number does not match the highestprimary key value in Exercise 6. Why?

� The CACHE value for WORKER_ID_SEQ is 5.

SQL> START p13q3

SET ECHO OFF

SEQUENCE_NAME CACHE_SIZE MAX_VALUE INCREMENT_BY LAST_NUMBER--------------- ---------- ---------- ------------ -----------DEPT_ID_SEQ 0 80 1 78WORKER_ID_SEQ 5 9999999 1 209

8. Execute p13q4.sql to insert four additional departments named Accounting,Warehouse, Operations, and Research. What happened and why?

SQL> START p13q4

SQL> SET ECHO OFFEnter the department name: Accounting

1 row created.

SQL> START p13q4

SQL> SET ECHO OFFEnter the department name: Warehouse

1 row created.

SQL> START p13q4

SQL> SET ECHO OFFEnter the department name: Operations

1 row created.

Page 96: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������#�

�������� �� ����� ���������

8.—continued

SQL> START p13q4

SQL> SET ECHO OFFEnter the department name: ResearchVALUES (’Research’,dept_id_seq.NEXTVAL) *ERROR at line 2: ORA-08004: sequence DEPT_ID_SEQ.NEXTVAL exceeds MAXVALUE and cannot be instantiated

� Reached maxvalue for DEPT_ID_SEQ.

9. Modify your department sequence to allow no maximum value. Verify the changeto the sequence by executing the p13q3.sql script.

SQL> ALTER SEQUENCE dept_id_seq NOMAXVALUE;

Sequence altered.

SQL> START p13q3

SET ECHO OFF

SEQUENCE_NAME CACHE_SIZE MAX_VALUE INCREMENT_BY LAST_NUMBER--------------- ---------- ---------- ------------ -----------DEPT_ID_SEQ 0 1.0000E+27 1 80WORKER_ID_SEQ 5 9999999 1 209

Page 97: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��#�

�������� �� ����� ���������

10. Add the Research department by using your script named p13q4.sql. Make thisaddition permanent.

SQL> START p13q4

SQL> SET ECHO OFFEnter the department name: Research

1 row created.

SQL> COMMIT;

Commit complete.

11. Display the contents of the DEPARTMENT table and WORKER table.

SQL> SELECT *2 FROM department;

ID NAME ---- ------------------------- 10 Finance 37 Marketing 76 Education 75 Human Resources 54 Sales 77 Administration 78 Accounting 79 Warehouse 80 Operations 81 Research

10 rows selected.

Page 98: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������#

�������� �� ����� ���������

11.—continued

SQL> SELECT *2 FROM worker;

ID LAST_NAME FIRST_NAME DEPT_ID TITLE---- ---------- ---------- -------- --------------- 200 Smith Donna 10 204 Lira Tomas 77 President 202 Korsgaard Harry 75 203 Guiliani Rey 37 205 Seigler Anna 10 Vice President

Page 99: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��#!

�������� �� �����

1. Create a view called EMP_VU based on the employee number, last name, anddepartment number from the WORKER table. Change the heading for the lastname to EMPLOYEE.

SQL> CREATE VIEW EMP_VU AS2 SELECT id, last_name employee, 3 dept_id5 FROM worker;

View created.

a. Display the content of the EMP_VU view.

SQL> SELECT *2 FROM emp_vu;

ID EMPLOYEE DEPARTMENT_ID--------- ------------------------- ------------- 200 Smith 10 202 Korsgaard 75 203 Guiliani 37 204 Lira 77 205 Seigler 10

Page 100: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������#"

�������� �� ����� ���������

1.—continued

b. Write a script to display the definition of a view. Pass the name of the view tothe script. Save the script as p14q1.sql. Execute the script to view thedefinition of the EMP_VU view.

SET ECHO OFFSET VERIFY OFFSET LONG 200COLUMN view_name FORMAT A15COLUMN text FORMAT A50SELECT *FROM user_viewsWHERE view_name = UPPER(’&view’)/COLUMN text CLEARCOLUMN view_name CLEARSET LONG 80SET ECHO ON

SQL> START p14q1

SQL> SET ECHO OFFEnter value for view: emp_vu

VIEW_NAME TEXT_LENGTH TEXT--------------- ----------- ------------------------------EMP_VU 60 SELECT id, last_name employee, dept_id FROM worker

c. Change the department number for Smith to 37 in the EMP_VU view.

SQL> UPDATE emp_vu2 SET dept_id = 373 WHERE employee = ’Smith’;

1 row updated.

Page 101: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��##

�������� �� ����� ���������

1.—continued

d. Confirm that Smith is now assigned to department 37.

SQL> SELECT *2 FROM emp_vu;

ID EMPLOYEE DEPARTMENT_ID--------- ------------------------- ------------- 200 Smith 37 202 Korsgaard 75 203 Guiliani 37 204 Lira 77 205 Seigler 10

2. Create a view called MNS_VU that contains the employee number, full name, anddepartment name for all employees in the Marketing and Sales departments in theWORKER and DEPARTMENT tables. Save the command in a script namedp14q2.sql.

SQL> CREATE OR REPLACE VIEW mns_vu AS2 SELECT w.id, w.first_name||’ ’||w.last_name3 full_name, d.name4 FROM worker w, department d5 WHERE w.dept_id = d.id6 AND d.id IN (37, 54);

View created.

Page 102: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$$

�������� �� ����� ���������

2.—continued

a. Display the structure and contents of the MNP_VU view.

SQL> DESCRIBE mns_vu

Name Null? Type----------------------------- -------- ----ID NOT NULL NUMBER(7)FULL_NAME VARCHAR2(51)NAME VARCHAR2(25)

SQL> SELECT *2 FROM mns_vu;

ID FULL_NAME NAME--------- ------------------------ ------------- 200 Donna Smith Marketing 203 Rey Guiliani Marketing

b. Display the definition of the MNS_VU view by executing the p14q1.sqlscript.

SQL> START p14q1

SQL> SET ECHO OFFEnter value for view: mns_vu

VIEW_NAME TEXT_LENGTH TEXT-------------- ----------- ------------------------------MNS_VU 140 SELECTw.id, w.first_name||’ ’ ||w.last_name full_name, d.nam e FROM worker w, dept d WHERE w.dept_id = d.id AND d.id IN (37, 54)

Page 103: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���$�

�������� �� ����� ���������

2.—continued

c. Display the department name and number of employees in each department.

SQL> SELECT name, COUNT(*)2 FROM mns_vu3 GROUP BY name;

NAME COUNT(*)------------------------- ---------Marketing 2

3. Modify EMP_VU view to contain only those employees in department 37. Add acheck constraint so that the department number cannot be modified.

SQL> CREATE OR REPLACE VIEW EMP_VU AS2 SELECT id, last_name employee, 3 dept_id4 FROM worker5 WHERE dept_id = 376 WITH CHECK OPTION CONSTRAINT emp_dept_id_37;

View created.

a. Display the contents of the EMP_VU view.

SQL> SELECT *2 FROM emp_vu;

ID EMPLOYEE DEPT_ID--------- ------------------------- ------------- 200 Smith 37 203 Guiliani 37

Page 104: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$�

�������� �� ����� ���������

3.—continued

b. Change the department number for Smith back to 54 through the EMP_VUview. Was your operation successful? Why or why not?

SQL> UPDATE emp_vu2 SET dept_id = 543 WHERE employee = ’Smith’;

WHERE employee = ’Smith’ *ERROR at line 3:ORA-01402: view WITH CHECK OPTION where-clauseviolation

� The operation was unsuccessful because the CHECK OPTIONconstraint does not allow the department number to be changed in theview.

4. Modify the MNS_VU so that the rows can only be seen between 1:00 P.M. and4:00 P.M. You can edit the script named p14q2.sql. Execute the script. Display thecontents of the view.

CREATE OR REPLACE VIEW MNS_VUAS SELECT w.id, w.first_name||’ ’||w.last_name

full_name, d.nameFROM worker w, department dWHERE w.dept_id = d.idAND d.id IN (37, 54)AND TO_CHAR(SYSDATE,’hh24mi’)BETWEEN ’1300’ and ’1600’;

SQL> START p14q2

View created.

Page 105: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���$�

�������� �� ����� ���������

4.—continued

� If your server’s time is between the time range specified, you will seethe following result. Otherwise, the SELECT statement yields no rows.

SQL> SELECT *2 FROM mns_vu;

ID FULL_NAME NAME--------- ------------------------ --------------- 200 Donna Smith Marketing 203 Rey Guiliani Marketing

5. Remove all views from the data dictionary. Confirm that no views exist in thedata dictionary.

SQL> SELECT view_name2 FROM user_views;

VIEW_NAME------------------------------EMP_VUMNS_VU

SQL> DROP VIEW emp_vu;

View dropped.

SQL> DROP VIEW mns_vu;

View dropped.

Page 106: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$�

�������� �� ����� ���������

5.—continued

SQL> SELECT view_name2 FROM user_views;

no rows selected

Page 107: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���$�

�������� �� �����

1. Would an indexes specified be used with the following queries and why?

a. Non-unique index on LAST_NAME.

� Yes because the LAST_NAME column is used in the WHERE clause.

SQL> SELECT *2 FROM s_emp3 WHERE last_name = ’Biri’;

b. Unique index on ID and non-unique index on CUSTOMER_ID.

� No because the WHERE clause does not specify a column that has anindex on it.

SQL> SELECT id, customer_id, total2 FROM s_ord3 WHERE date_ordered = ’31-AUG-92’;

c. Unique index on S_DEPT.ID and non-unique index on S_EMP.DEPT_ID.

� Yes because both columns are in the WHERE clause.

SQL> SELECT e.last_name, d.name2 FROM s_emp e, s_dept d3 WHERE e.dept_id = d.id;

Page 108: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$

�������� �� ����� ���������

2. Create a non-unique index on the foreign key column in the WORKER table.

SQL> CREATE INDEX worker_dept_id_idx2 ON worker(dept_id);

Index created.

3. Since users will frequently query on the employee last name, create a non-uniqueindex on that column in the WORKER table.

SQL> CREATE INDEX worker_last_name_idx2 ON worker(last_name);

Index created.

4. Display the indexes and uniqueness that exist in the data dictionary for theWORKER and DEPARTMENT tables. Save the command into a script namedp15q4.sql.

SET ECHO OFFCOLUMN index_name FORMAT A20COLUMN table_name FORMAT A15SELECT index_name, table_name, uniquenessFROM user_indexesWHERE table_name IN (’WORKER’,’DEPARTMENT’)/COLUMN index_name CLEARCOLUMN table_name CLEARSET ECHO ON

Page 109: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���$!

�������� �� ����� ���������

4.—continued

SQL> START p15q4

SET ECHO OFF

INDEX_NAME TABLE_NAME UNIQUENES-------------------- --------------- ---------DEPT_ID_PK DEPARTMENT UNIQUEWORKER_DEPT_ID_IDX WORKER NONUNIQUEWORKER_ID_PK WORKER UNIQUEWORKER_LAST_NAME_IDX WORKER NONUNIQUE

5. Remove the primary key constraint on the WORKER table.

SQL> ALTER TABLE worker2 DROP CONSTRAINT worker_id_pk;

Table altered.

6. Re-display the indexes and uniqueness that exist in the data dictionary for theWORKER and DEPARTMENT tables by executing the p15q4.sql script. Whatchanges do you observe and why?

� The WORKER_ID_PK index is no longer in the list because when theprimary key constraint on the WORKER table was dropped, the index wasno longer required and therefore automatically removed.

SQL> START p15q4

SET ECHO OFF

INDEX_NAME TABLE_NAME UNIQUENES-------------------- --------------- ---------DEPT_ID_PK DEPARTMENT UNIQUEWORKER_DEPT_ID_IDX WORKER NONUNIQUEWORKER_LAST_NAME_IDX WORKER NONUNIQUE

Page 110: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$"

�������� �� ����� ���������

7. Re-create the primary key constraint on the WORKER table. Confirm theconstraint in the data dictionary by executing pl2q2.sql. Confirm the unique indexin the data dictionary by executing pl5q4.

SQL> ALTER TABLE worker2 ADD CONSTRAINT worker_id_pk PRIMARY KEY(id);

Table altered.

SQL> START pl2q2

CONSTRAINT_NAME C------------------- -SYS_C00108623 CSYS_C00108624 CWORKER_ID_PK PWORKER_DEPT_ID_FK R

SQL> START p15q4

SET ECHO OFF

INDEX_NAME TABLE_NAME UNIQUENES-------------------- --------------- ---------DEPT_ID_PK DEPARTMENT UNIQUEWORKER_DEPT_ID_IDX WORKER NONUNIQUEWORKER_ID_PK WORKER UNIQUEWORKER_LAST_NAME_IDX WORKER NONUNIQUE

8. Remove the index on the employee last name from the WORKER table.

SQL> DROP INDEX worker_last_name_idx;

Index dropped.

Page 111: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���$#

�������� � �����

1. What privilege should a user be given to log in to the Oracle7 Server? Is thisprivilege a system or object privilege?

� The CREATE SESSION system privilege.

2. What privilege should a user be given to create tables?

� The CREATE TABLE privilege.

3. If you create a table, who can pass along privileges to other users on your table?

� You can, or anyone you have given those privileges to by using the WITHGRANT OPTION.

4. You are the DBA. You are creating many users who require the same systemprivileges. What would you use to make your job easier?

� Create a role containing the system privileges and allocate the role to theusers.

5. What command do you use to change your password?

� The ALTER USER command.

6. Grant other users query access to your S_REGION table. Have them grant youquery access to their S_REGION table.

� Team 2 executes the GRANT command.

SQL> GRANT select2 ON s_region3 TO user1;

Grant succeeded.

� Team 1 executes the GRANT command.

SQL> GRANT select2 ON s_region3 TO user2;

Grant succeeded.

� Where user1 is the name of team 1 and user2 is the name of team 2.

Page 112: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������$

�������� � ����� ���������

7. Query all the rows in your S_REGION table.

SQL> SELECT *2 FROM s_region;

ID NAME------- --------------- 1 North America 2 South America 3 Africa / Middle East 4 Asia 5 Europe

8. Add a new row to your S_REGION table. Team 1 should add Central America asregion number 6. Team 2 should add Micronesia as region number 7. Make thechanges permanent.

� Team 1 executes this INSERT command.

SQL> INSERT INTO s_region (id, name)2 VALUES (6, ’Central America’);

1 row created.

SQL> COMMIT;

Commit completed.

� Team 2 executes this INSERT command.

SQL> INSERT INTO s_region (id, name)2 VALUES (7, ’Micronesia’);

1 row created.

SQL> COMMIT;

Commit completed.

Page 113: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� � ����� ���������

9. Query the other team’s S_REGION table.

� Team 1 executes the query.

SQL> SELECT *2 FROM user2.s_region;

ID NAME------- --------------- 1 North America 2 South America 3 Africa / Middle East 4 Asia 5 Europe 7 Micronesia

6 rows selected.

� Team 2 executes the query.

SQL> SELECT *2 FROM user1.s_region;

ID NAME------- --------------- 1 North America 2 South America 3 Africa / Middle East 4 Asia 5 Europe 6 Centeral America

6 rows selected.

Page 114: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� � ����� ���������

10. Create a synonym for the other team’s S_REGION table.

� Team 1 creates a synonym named team2.

SQL> CREATE SYNONYM team22 FOR user2.s_region;

Synonynm created.

� Team 2 creates a synonym named team1.

SQL> CREATE SYNONYM team12 FOR user1.s_region;

Synonynm created.

11. Display the other team’s S_REGION table contents by using your synonym.

� Team 1 executes the query.

SQL> SELECT *2 FROM team2;

ID NAME------- --------------- 1 North America 2 South America 3 Africa / Middle East 4 Asia 5 Europe 7 Micronesia

6 rows selected.

Page 115: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� � ����� ���������

11.—continued

� Team 2 executes the query.

SQL> SELECT *2 FROM team1;

ID NAME------- --------------- 1 North America 2 South America 3 Africa / Middle East 4 Asia 5 Europe 6 Central America

6 rows selected.

12. Confirm the privileges in effect for your team’s tables.

� Team 1 executes the query.

SQL> SELECT *2 FROM user_tab_privs_made;

GRANTEE TABLE_NAME GRANTOR PRIVILEGE GRA-------- ------------ -------- --------- ---user2 S_REGION user1 SELECT NO

Page 116: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� � ����� ���������

12.—continued

� Team 2 executes the query.

SQL> SELECT *2 FROM user_tab_privs_made;

GRANTEE TABLE_NAME GRANTOR PRIVILEGE GRA-------- ------------ -------- --------- ---user1 S_REGION user2 SELECT NO

13. Revoke the SELECT privilege from the other team.

� Team 1 revokes the privilege.

SQL> REVOKE select2 ON s_region3 FROM user2;

Revoke succeeded.

� Team 2 revokes the privilege.

SQL> REVOKE select2 ON s_region3 FROM user1;

Revoke succeeded.

Page 117: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� � ����� ���������

14. Attempt to SELECT from the other team’s S_REGION table.

� Team 1 executes the query.

SQL> SELECT *2 FROM team2;

Error at line 1:ORA-00942: table or view does not exist

� Team 2 executes the query.

SQL> SELECT *2 FROM team1;

Error at line 1:ORA-00942: table or view does not exist

15. Drop the synonym you created.

� Team 1 drops the synonym.

SQL> DROP SYNONYM team2;

Synonym dropped.

� Team 2 drops the synonym.

SQL> DROP SYNONYM team1;

Synonym dropped.

Page 118: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� �! �����

1. Create the tables based on the entity relationship diagram on the previous pageand the table instance charts below. Choose the appropriate datatypes and be sureto add the integrity constraints.

a. Table name: MEMBER

ColumnName

MEMBER_ID

LAST_NAME

FIRST_NAME

ADDRESS CITY PHONE JOIN_DATE

KeyType

PK

Null/Unique

NN, U NN NN

DefaultValue

System date

Datatype number char char char char char date

Length 10 25 25 100 30 15

SQL> CREATE TABLE MEMBER2 (member_id NUMBER (10)3 CONSTRAINT member_id_pk PRIMARY KEY,4 last_name VARCHAR2(25)5 CONSTRAINT member_last_nn NOT NULL,6 first_name VARCHAR2(25),7 address VARCHAR2(100),8 city VARCHAR2(30),9 phone VARCHAR2(15),10 join_date DATE DEFAULT SYSDATE11 CONSTRAINT join_date_nn NOT NULL);

Table created.

Page 119: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����!

�������� �! ����� ���������

1.—continued

b. Table name: TITLE

ColumnName

TITLE_ID TITLE DESCRIPTION RATING CATEGORY

RELEASE_DATE

KeyType

PK

Null/Unique

NN, U NN NN

Check G, PG,R,NC17,NR

DRAMA,COMEDY,ACTION,CHILD, SCIFI,DOCUMENTARY

DefaultValue

DRAMA

Datatype number char char char char date

Length 10 60 400 4 20

Page 120: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������"

�������� �! ����� ���������

1b.—continued

SQL> CREATE TABLE title2 (title_id NUMBER(10)3 CONSTRAINT title_id_pk PRIMARY KEY,4 title VARCHAR2(60)5 CONSTRAINT title_nn NOT NULL,6 description VARCHAR2(400)7 CONSTRAINT title_desc_nn NOT NULL,8 rating VARCHAR2(4)9 CONSTRAINT title_rating_ck CHECK10 (rating IN (’G’,’PG’,’R’,’NC17’,’NR’)),11 category VARCHAR2(20) DEFAULT ’DRAMA’12 CONSTRAINT title_categ_ck CHECK13 (category IN (’DRAMA’, ’COMEDY’, ’ACTION’,14 ’CHILD’, ’SCIFI’, ’DOCUMENTARY’)),15 release_date DATE);

Table created.

Page 121: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����#

�������� �! ����� ���������

1.—continued

c. Table name: TITLE_COPY

ColumnName

COPY_ID TITLE_ID STATUS

Key Type PK PK, FK

Null/Unique

NN, U NN, U NN

Check AVAILABLE, DESTROYED,RENTED, RESERVED

FK RefTable

title

FK Ref Col title_id

Datatype number number char

Length 10 10 15

SQL> CREATE TABLE title_copy2 (copy_id NUMBER(10),3 title_id NUMBER(10)4 CONSTRAINT copy_title_id_fk REFERENCES5 title(title_id),6 status VARCHAR2(15)7 CONSTRAINT copy_status_nn NOT NULL 8 CONSTRAINT copy_status_ck CHECK9 (status IN (’AVAILABLE’, ’DESTROYED’,

10 ’RENTED’, ’RESERVED’)),11 CONSTRAINT copy_title_id_pk 12 PRIMARY KEY(copy_id, title_id));

Table created.

Page 122: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������$

�������� �! ����� ���������

1.—continued

d. Table name: RENTAL

ColumnName

BOOK_DATE

MEMBER_ID

COPY_ID ACT_RET_DATE

EXP_RET_DATE

TITLE_ID

Key Type PK FK PK, FK PK, FK

Null/Unique

NN,U NN NN,U NN,U

DefaultValue

Systemdate

2 daysafter bookdate

FK RefTable

member title_copy title_copy

FK RefCol

member_id copy_id title_id

Datatype date number number date date number

Length 10 10 10

SQL> CREATE TABLE rental2 (book_date DATE DEFAULT SYSDATE,3 member_id NUMBER(10)4 CONSTRAINT rental_mbr_id_fk 5 REFERENCES member(member_id),6 copy_id NUMBER(10),7 act_ret_date DATE,8 exp_ret_date DATE DEFAULT SYSDATE + 2,9 CONSTRAINT rental_copy_title_id_fk 10 FOREIGN KEY (copy_id, title_id)11 REFERENCES title_copy(copy_id, title_id),12 title_id NUMBER(10),13 CONSTRAINT rental_id_pk PRIMARY KEY14 (book_date, copy_id, title_id));

Table created.

Page 123: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

1.—continued

e. Table name: RESERVATION

Column Name RES_DATE MEMBER_ID TITLE_ID

Key Type PK PK, FK PK, FK

Null/Unique

NN,U NN,U NN,U

FK Ref Table member title

FK Ref Col member_id title_id

Datatype date number number

Length 10 10

SQL> CREATE TABLE reservation2 (res_date DATE,3 member_id NUMBER(10)4 CONSTRAINT res_member_id_fk5 REFERENCES member (member_id),6 title_id NUMBER(10)7 CONSTRAINT res_title_id_fk8 REFERENCES title (title_id),9 CONSTRAINT res_id_pk PRIMARY KEY10 (res_date, member_id, title_id));

Table created.

Page 124: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �! ����� ���������

2. Verify that the tables and constraints were created properly by checking the datadictionary.

SQL> SELECT object_name2 FROM user_objects3 WHERE object_name IN (’MEMBER’,’TITLE’,4 ’TITLE_COPY’,’RENTAL’,’RESERVATION’);

OBJECT_NAME-------------------RESERVATIONRENTALTITLE_COPYTITLEMEMBER

SQL> SELECT constraint_name, constraint_type, 2 table_name, search_condition,3 r_constraint_name4 FROM user_constraints5 WHERE table_name IN (’MEMBER’,’TITLE’,6 ’TITLE_COPY’,’RENTAL’,’RESERVATION’);

Page 125: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

2.—continued

CONSTRAINT_NAME C TABLE_NAME SEARCH_CONDITIONR_CONSTRAINT_NAME-------------------- - --------------- ---------------------–-----------------–––MEMBER_LAST_NN C MEMBER LAST_NAME IS NOT NULLJOIN_DATE_NN C MEMBER JOIN_DATE IS NOT NULLMEMBER_ID_PK P MEMBERRENTAL_ID_PK P RENTALRENTAL_MBR_ID_FK R RENTALMEMBER_ID_PKRENTAL_COPY_TITLE_ID R RENTALCOPY_TITLE_ID_PK_FKRES_MEMBER_ID_FK R RESERVATIONMEMBER_ID_PKRES_TITLE_ID_FK R RESERVATIONTITLE_ID_PKRES_ID_PK P RESERVATIONTITLE_NN C TITLE TITLE IS NOT NULLTITLE_DESC_NN C TITLE DESCRIPTION IS NOT NU LLTITLE_ID_PK P TITLETITLE_RATING_NN C TITLE RATING IS NOT NULLTITLE_RATING_CK C TITLE rating IN (’G’,’PG’, ’R’,’NC17’,’NR’)TITLE_CATEG_NN C TITLE RATING IS NOT NULLTITLE_CATEG_CK C TITLE category IN (’DRAMA’, ’COMEDY’,’ACTION’, ’CHILD’,’SCIFI’, ’DOCUMENTARY’)COPY_STATUS_NN C TITLE_COPY STATUS IS NOT NULLCOPY_STATUS_CK C TITLE_COPY status IN (’AVAILABLE’, ’DESTROYED’,’RENTED’, ’RESERVED’)COPY_TITLE_ID_PK P TITLE_COPYCOPY_TITLE_ID_FK R TITLE_COPY

16 rows selected.

Page 126: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �! ����� ���������

3. Create sequences to uniquely identify each row in the MEMBER table and theTITLE table.

a. Member number for the MEMBER table, start with 101, do not allow cachingof the values.

SQL> CREATE SEQUENCE member_id_seq2 START WITH 1013 NOCACHE;

Sequence created.

b. Title number for the TITLE table, start with 92, no caching.

SQL> CREATE SEQUENCE title_id_seq2 START WITH 923 NOCACHE;

Sequence created.

c. Verify the existence of the sequences in the data dictionary.

SQL> SELECT sequence_name, increment_by, 2 last_number3 FROM user_sequences4 WHERE sequence_name IN (’MEMBER_ID_SEQ’,5 ’TITLE_ID_SEQ’);

SEQUENCE_NAME INCREMENT_BY LAST_NUMBER--------------- ------------ -----------MEMBER_ID_SEQ 1 101TITLE_ID_SEQ 1 92

Page 127: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

4. Add data to the tables. Create a script for each set of data to add.

a. Add movie titles to the TITLE table. Write a script to enter the movieinformation. Save the script as p17q4a.sql. Use the sequence to uniquelyidentify each title. Remember that single quotation marks in a character fieldmust be specially handled. Verify your additions.

Title Description Rating Category Release date

Willie andChristmasToo

All of Willie’s friends made aChristmas list for Santa, butWillie has yet to add his ownwish list.

G CHILD 05-OCT-95

Alien Again Yet another installment ofscience fiction history. Canthe heroine save the planetfrom the alien life form?

R SCIFI 19-MAY-95

The Glob A meteor crashes near asmall American town andunleashes carnivorous goo inthis classic.

NR SCIFI 12-AUG-95

My Day Off With a little luck and a lot ofingenuity, a teenager skipsschool for a day in NewYork.

PG COMEDY 12-JUL-95

Miracles onIce

A six-year-old has doubtsabout Santa Claus. But shediscovers that miracles reallydo exist.

PG DRAMA 12-SEP-95

Soda Gang After discovering a cache ofdrugs, a young couple findthemselves pitted against avicious gang.

NR ACTION 01-JUN-95

Page 128: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� �! ����� ���������

4a.—continued

SET ECHO OFFINSERT INTO title (title_id, title, description,

rating, category, release_date)VALUES (title_id_seq.nextval,

’Willie and Christmas Too’, ’All of Willie’’s friends made a Christmas list for Santa, but Willie has yet to add his own wish list.’,’G’,’CHILD’,’05-OCT-95’)/INSERT INTO title (title_id, title, description,

rating, category, release_date)VALUES (title_id_seq.nextval, ’Alien Again’,

’Yet another installment of science fictionhistory. Can the heroine save the planet from thealien life form?’, ’R’, ’SCIFI’, ’19-MAY-95’)/INSERT INTO title (title_id, title, description,

rating, category, release_date)VALUES (title_id_seq.nextval, ’The Glob’, ’A meteor crashes near a small American town and unleashescarnivorous goo in this classic.’, ’NR’, ’SCIFI’, ’12-AUG-95’)/INSERT INTO title (title_id, title, description,

rating, category, release_date)VALUES (title_id_seq.nextval, ’My Day Off’, ’With a little luck and a lot of ingenuity, a teenager skips school for a day in New York.’, ’PG’, ’COMEDY’, ’12-JUL-95’)/

Page 129: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����!

�������� �! ����� ���������

4a.—continued

INSERT INTO title (title_id, title, description,rating, category, release_date)

VALUES (title_id_seq.nextval, ’Miracles on Ice’, ’A six-year-old has doubts about Santa Claus. But she discovers that miracles really do exist.’, ’PG’, ’DRAMA’, ’12-SEP-95’)/INSERT INTO title (title_id, title, description,

rating, category, release_date)VALUES (title_id_seq.nextval, ’Soda Gang’, ’After discovering a cache of drugs, a young couple find themselves pitted against a vicious gang.’, ’NR’, ’ACTION’, ’01-JUN-95’)/COMMIT/SET ECHO ON

SQL> START p17q4a

SET ECHO OFF1 row created.1 row created.1 row created.1 row created.1 row created.1 row created.Commit complete.

Page 130: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������"

�������� �! ����� ���������

4a.—continued

SQL> SELECT *2 FROM title3 ORDER BY title_id;

TITLE_ID TITLE---------- -------------------------DESCRIPTION-------------------------------------------------RATI CATEGORY RELEASE_D---- -------------------- --------- 92 Willie and Christmas TooAll of Willie’s friends made a Christmas list forSanta, but Willie has yet to create his ownwish list.G CHILD 05-OCT-95

93 Alien AgainAnother installment of science fiction history.Can the heroine save the planet from the alienlife form?R SCIFI 19-MAY-95

94 The GlobA meteor crashes near a small American town andunleashes carnivorous goo in this classic.NR SCIFI 12-AUG-95

95 My Day OffWith a little luck and a lot of ingenuity, ateenager skips school for a day in New York.PG COMEDY 12-JUL-95

Page 131: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����#

�������� �! ����� ���������

4a.—continued

TITLE_ID TITLE---------- -------------------------DESCRIPTION-------------------------------------------------RATI CATEGORY RELEASE_D---- -------------------- ---------

96 Miracles on IceA six-year-old has doubts about Santa Claus. Butshe discovers that miracles really do exist.PG DRAMA 12-SEP-95

97 Soda GangAfter discovering a cached of drugs, a youngcouple find themselves pitted against a viciousgang.NR ACTION 01-JUN-95

6 rows selected.

Page 132: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������$

�������� �! ����� ���������

4.—continued

b. Add data to the MEMBER table. Write a script named p17q4b.sql to promptusers for the information. Execute the script. Be sure to use the sequence toadd the member numbers.

Firstname Last name Address City Phone Join date

Carmen Velasquez 283 KingStreet

Seattle 206-899-6666 08-MAR-90

LaDoris Ngao 5Modrany

Bratislava 586-355-8882 08-MAR-90

Midori Nagayama 68 ViaCentrale

Sao Paolo 254-852-5764 17-JUN-91

Mark Quick-To-See 6921 KingWay

Lagos 63-559-7777 07-APR-90

Audry Ropeburn 86 ChuStreet

HongKong

41-559-87 18-JAN-91

Molly Urguhart 3035LaurierBlvd

Quebec 418-542-9988 18-JAN-91

� Script p17q4b.sql contents.

SET ECHO OFFINSERT INTO member (member_id, first_name, last_name,

address, city, phone, join_date)VALUES (member_id_seq.NEXTVAL, ’&first_name’,

’&last_name’, ’&address’,’&city’,’&phone’,’&join_date’)

/COMMIT/SET ECHO ON

Page 133: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

4b.—continued

SQL> START p17q4b

SET ECHO OFFEnter value for first_name: CarmenEnter value for last_name: VelasquezEnter value for address: 283 King StreetEnter value for city: SeattleEnter value for phone: 206-899-6666Enter value for join_date: 08-MAR-901 row created.Commit complete.

SQL> START p17q4b

SET ECHO OFFEnter value for first_name: LaDorisEnter value for last_name: NgaoEnter value for address: 5 ModranyEnter value for city: BratislavaEnter value for phone: 586-355-8882Enter value for join_date: 08-MAR-901 row created.Commit complete.

SQL> START p17q4b

SET ECHO OFFEnter value for first_name: MidoriEnter value for last_name: NagayamaEnter value for address: 68 Via CentraleEnter value for city: Sao PaoloEnter value for phone: 254-852-5764Enter value for join_date: 17-JUN-911 row created.Commit complete.

Page 134: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �! ����� ���������

4b.—continued

SQL> START p17q4b

SET ECHO OFFEnter value for first_name: MarkEnter value for last_name: Quick-To-SeeEnter value for address: 6921 King WayEnter value for city: LagosEnter value for phone: 63-559-7777Enter value for join_date: 07-APR-901 row created.Commit complete.

SQL> START p17q4b

SET ECHO OFFEnter value for first_name: AudryEnter value for last_name: RopeburnEnter value for address: 86 Chu StreetEnter value for city: Hong KongEnter value for phone: 41-559-87Enter value for join_date: 18-JAN-911 row created.Commit complete.

SQL> START p17q4b

SET ECHO OFFEnter value for first_name: MollyEnter value for last_name: UrguhartEnter value for address: 3035 Laurier BlvdEnter value for city: QuebecEnter value for phone: 418-542-9988Enter value for join_date: 18-JAN-911 row created.Commit complete.

Page 135: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

4b.—continued

� Verify the additions.

SQL> SELECT *2 FROM member3 ORDER BY member_id;

MEMBER_ID LAST_NAME FIRST_NAME ---------- ---------- ---------- ADDRESS CITY ------------------------------ ---------- PHONE JOIN_DATE --------------- --------- 101 Velasquez Carmen 283 King Street Seattle 206-899-6666 03-MAR-90 102 Ngao LaDoris 5 Modrany Bratislava 586-355-8882 08-MAR-90 103 Nagayama Midori 68 Via Centrale Sao Paolo 254-852-5764 17-JUN-91 104 Quick-To-S Mark ee 6921 King Way Lagos 63-559-777 07-APR-90

Page 136: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �! ����� ���������

4b.—continued

MEMBER_ID LAST_NAME FIRST_NAME ---------- ---------- ---------- ADDRESS CITY ------------------------------ ---------- PHONE JOIN_DATE --------------- --------- 105 Ropeburn Audry 86 Chu Street Hong Kong 41-559-87 04-MAR-90 106 Urguhart Molly 3035 Laurier Blvd. Quebec 418-542-9988 18-JAN-91

6 rows selected.

Page 137: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

4.—continued

c. Add the following movie copies in the TITLE_COPY table:

Title Copy number Status

Willie and Christmas Too 1 Available

Alien Again 1 Available

2 Rented

The Glob 1 Available

My Day Off 1 Available

2 Available

3 Rented

Miracles on Ice 1 Available

Soda Gang 1 Available

Page 138: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� �! ����� ���������

4c.—continued

� Script p17q4c.sql contents.

SET ECHO OFFINSERT INTO title_copy (copy_id, title_id, status)VALUES (1, 92, ’AVAILABLE’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (1, 93, ’AVAILABLE’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (2, 93, ’RENTED’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (1, 94, ’AVAILABLE’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (1, 95, ’AVAILABLE’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (2, 95, ’AVAILABLE’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (3, 95, ’RENTED’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (1, 96, ’AVAILABLE’)/INSERT INTO title_copy (copy_id, title_id, status)VALUES (1, 97, ’AVAILABLE’)/COMMIT/SET ECHO ON

Page 139: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����!

�������� �! ����� ���������

4c.—continued

SQL> START p17q4c

SET ECHO OFF1 row created.1 row created.1 row created.1 row created.1 row created.1 row created.1 row created.1 row created.1 row created.Commit complete.

� Verify the additions.

SQL> SELECT *2 FROM title_copy3 ORDER BY title_id, copy_id;

COPY_ID TITLE_ID STATUS ---------- ---------- --------------- 1 92 AVAILABLE 1 93 AVAILABLE 2 93 RENTED 1 94 AVAILABLE 1 95 AVAILABLE 2 95 AVAILABLE 3 95 RENTED 1 96 AVAILABLE 1 97 AVAILABLE

9 rows selected.

Page 140: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������"

�������� �! ����� ���������

4.—continued

d. Add the following rentals to the RENTAL table:

Title Copynumber

Customer Date rented Date returnexpected

Datereturned

Willie andChristmas Too

1 101 3 days ago 1 day ago 2 days ago

Alien Again 2 101 1 day ago 1 day fromnow

My Day Off 3 102 2 days ago Today

Soda Gang 1 106 4 days ago 2 days ago 2 days ago

SQL> INSERT INTO rental (title_id, copy_id2 member_id, book_date, exp_ret_date,3 act_ret_date)4 VALUES (92, 1, 101, SYSDATE-3,5 SYSDATE-1, SYSDATE-2);

1 row created.

SQL> INSERT INTO rental (title_id, copy_id2 member_id, book_date, exp_ret_date,3 act_ret_date)4 VALUES (93, 2, 101, SYSDATE-1,5 SYSDATE+1, null);

1 row created.

SQL> INSERT INTO rental (title_id, copy_id2 member_id, book_date, exp_ret_date,3 act_ret_date)4 VALUES (95, 3, 102, SYSDATE-2,5 SYSDATE, null);

1 row created.

Page 141: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����#

�������� �! ����� ���������

4d.—continued

SQL> INSERT INTO rental (title_id, copy_id2 member_id, book_date, exp_ret_date,3 act_ret_date)4 VALUES (97, 1, 106, SYSDATE-4,5 SYSDATE-2, SYSDATE-2);

1 row created.

SQL> COMMIT;

Commit complete

� Verify your additions.

SQL> SELECT *2 FROM rental3 ORDER BY title_id;

BOOK_DATE MEMBER_ID COPY_ID ACT_RET_D--------- ---------- ---------- ---------EXP_RET_D TITLE_ID--------- ----------07-FEB-96 101 1 08-FEB-9609-FEB-96 92

09-FEB-96 101 211-FEB-96 93

08-FEB-96 102 310-FEB-96 95

06-FEB-96 106 1 08-FEB-9608-FEB-96 97

Page 142: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������$

�������� �! ����� ���������

5. Create a view named TITLE_AVAIL to show the movie titles and the availabilityof each copy and its expected return date if rented. Query all rows from the view.

SQL> CREATE VIEW title_avail AS2 SELECT t.title, c.copy_id, c.status,3 r.exp_ret_date4 FROM title t, title_copy c, rental r5 WHERE t.title_id = c.title_id6 AND c.copy_id = r.copy_id(+)7 AND c.title_id = r.title_id(+);

View created.

SQL> SELECT *2 FROM title_avail3 ORDER BY title, copy_id;

TITLE COPY_ID STATUS EXP_RET_D --------------- -------- ---------- --------- Alien Again 1 AVAILABLE Alien Again 2 RENTED 11-FEB-96 Miracles on Ice 1 AVAILABLE My Day Off 1 AVAILABLE My Day Off 2 AVAILABLE My Day Off 3 RENTED 10-FEB-96 Soda Gang 1 AVAILABLE 08-FEB-96 The Glob 1 AVAILABLE Willie and 1 AVAILABLE 09-FEB-96 Christmas Too

9 rows selected.

Page 143: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

6. Make changes to data in the tables.

a. Add a new title. The movie is “Interstellar Wars”, which is rated PG, andclassified as a SCIFI movie. The release date is 07-JUL-77. The description is“Futuristic interstellar action movie. Can the rebels save the humans from theevil Empire?” Be sure to add a title copy record for two copies.

SQL> INSERT INTO title (title_id, title, 2 description, rating, category, release_date)3 VALUES (title_id_seq.nextval, 4 ’Interstellar Wars’, 5 ’Futuristic interstellar action movie. Can the 6 rebels save the humans from the evil Empire?’, 7 ’PG’, ’SCIFI’, ’07-JUL-77’);

1 row created.

� Obtain the title number for use in the TITLE_COPY table.

SQL> SELECT title_id, title2 FROM title3 WHERE title = ’Interstellar Wars’;

TITLE_ID TITLE---------- --------------------- 98 Interstellar Wars

� Insert a record for the copies into the TITLE_COPY table.

SQL> INSERT INTO title_copy (copy_id, title_id, 2 status)3 VALUES (1, 98, ’AVAILABLE’);

1 row created.

Page 144: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �! ����� ���������

6a.—continued

SQL> INSERT INTO title_copy (copy_id, title_id, 2 status)3 VALUES (2, 98, ’AVAILABLE’);

1 row created.

b. Enter two reservations. One reservation is for Carmen Velasquez who wantsto rent “Interstellar Wars.” The other is for Mark Quick-To-See who wants torent “Soda Gang”.

SQL> SELECT member_id, first_name, last_name2 FROM member3 WHERE last_name 4 IN (’Velasquez’,’Quick-To-See’);

MEMBER_ID FIRST_NAME LAST_NAME---------- ---------- ------------ 101 Carmen Velasquez 104 Mark Quick-To-See

SQL> SELECT title_id, title2 FROM title3 WHERE title4 IN (’Interstellar Wars’,’Soda Gang’);

TITLE_ID TITLE---------- --------------- 97 Soda Gang 98 Interstellar Wars

Page 145: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

6b.—continued

SQL> INSERT INTO reservation 2 (res_date, member_id, title_id)3 VALUES (sysdate, 101, 98);

1 row created.

SQL> INSERT INTO reservation 2 (res_date, member_id, title_id)2 VALUES (sysdate, 104, 97);

1 row created.

SQL> COMMIT;

Commit complete.

� Verify additions.

SQL> SELECT *2 FROM reservation;

RES_DATE MEMBER_ID TITLE_ID--------- ---------- ----------10-FEB-96 101 9810-FEB-96 104 97

Page 146: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �! ����� ���������

6.—continued

c. Customer Carmen Velasquez rents the movie “Interstellar Wars”, copy 1.Remove her reservation for the movie. Record the information about therental. Allow the default value for the expected return date to be used. Verifythe rental was recorded by using the view you created.

� Add the rental information.

SQL> INSERT INTO rental (title_id, copy_id,2 member_id)3 VALUES (98, 1, 101);

1 row created.

� Update the title copy information to show that the film is rented.

SQL> UPDATE title_copy2 SET status = ’RENTED’3 WHERE title_id = 984 AND copy_id = 1;

1 row updated.

� Remove the reservation.

SQL> DELETE FROM reservation2 WHERE member_id = 101;

1 row deleted.

Page 147: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

6c.—continued

� Confirm the rental information from the TITLE_AVAIL view.

SQL> SELECT *2 FROM title_avail;

TITLE COPY_ID STATUS EXP_RET_D --------------- -------- ---------- --------- Willie and 1 AVAILABLE 09-FEB-96 Christmas Too Alien Again 1 AVAILABLE The Glob 1 AVAILABLE My Day Off 1 AVAILABLE Miracles on Ice 1 AVAILABLE Soda Gang 1 AVAILABLE 08-FEB-96 Interstellar 1 RENTED 12-FEB-96 Wars Alien Again 2 RENTED 11-FEB-96 My Day Off 2 AVAILABLE Interstellar 2 AVAILABLE Wars My Day Off 3 RENTED 10-FEB-96

11 rows selected.

Page 148: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� �! ����� ���������

7. Make a modification to one of the tables.

a. Add a PRICE column to the TITLE table to record the purchase price of thevideo. The column should have a total length of eight digits and two decimalplaces. Verify your modification.

SQL> ALTER TABLE title2 ADD (price NUMBER(8,2));

Table altered.

SQL> DESCRIBE title

Name Null? Type-------------------------- -------- ----TITLE_ID NOT NULL NUMBER(10)TITLE NOT NULL VARCHAR2(60)DESCRIPTION NOT NULL VARCHAR2(400)RATING VARCHAR2(4)CATEGORY VARCHAR2(20)RELEASE_DATE DATEPRICE NUMBER(8,2)

Page 149: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����!

�������� �! ����� ���������

7.—continued

b. Create a script named p17q7b.sql to update each video with a price accordingto the following list:

Title Price

Willie and Christmas Too 25

Alien Again 35

The Glob 35

My Day Off 35

Miracle on Ice 98

Soda Gang 35

Interstellar Wars 29

� Script p17q7b.sql contents.

SET ECHO OFFUPDATE titleSET price = &priceWHERE title_id = &title_id/SET ECHO ON

SQL> START p17q7b

SET ECHO OFFEnter value for price: 25Enter value for title_id: 92

1 row updated.

Page 150: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������"

�������� �! ����� ���������

7b.—continued

SQL> START p17q7b

SET ECHO OFFEnter value for price: 35Enter value for title_id: 93

1 row updated.

SQL> START p17q7b

SET ECHO OFFEnter value for price: 35Enter value for title_id: 94

1 row updated.

SQL> START p17q7b

SET ECHO OFFEnter value for price: 35Enter value for title_id: 95

1 row updated.

SQL> START p17q7b

SET ECHO OFFEnter value for price: 98Enter value for title_id: 96

1 row updated.

Page 151: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����#

�������� �! ����� ���������

7b.—continued

SQL> START p17q7b

SET ECHO OFFEnter value for price: 35Enter value for title_id: 97

1 row updated.

SQL> START p17q7b

SET ECHO OFFEnter value for price: 29Enter value for title_id: 98

1 row updated.

SQL> COMMIT;

Commit complete.

� Verify the changes.

SQL> SELECT title_id, title, price2 FROM title3 ORDER BY title_id;

Page 152: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������$

�������� �! ����� ���������

7b.—continued

TITLE_ID TITLE PRICE---------- --------------- ---------- 92 Willie and 25 Christmas Too

93 Alien Again 35 94 The Glob 35 95 My Day Off 35 96 Miracles on Ice 98 97 Soda Gang 35 98 Interstellar 29 Wars

7 rows selected.

c. Ensure that in the future all titles will contain a price value. Verify theconstraint.

SQL> ALTER TABLE title2 MODIFY (price CONSTRAINT 3 member_price_nn NOT NULL);

Table altered.

SQL> SELECT constraint_name, constraint_type,2 search_condition, r_constraint_name3 FROM user_constraints4 WHERE table_name = ’TITLE’;

Page 153: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

7c.—continued

CONSTRAINT_NAME C SEARCH_CONDITION--------------- - --------------------R_CONSTRAINT_NA---------------TITLE_NN C TITLE IS NOT NULL

TITLE_DESC_NN C DESCRIPTION IS NOT NULL

TITLE_ID_PK P

TITLE_RATING_CK C rating IN (’G’,’PG’, ’R’,’NC17’,’NR’)

TITLE_CATEG_CK C category IN (’DRAMA’ ,’COMEDY’,’ACTION’, ’CHILD’,’SCIFI’, ’DOCUMENTARY’)

MEMBER_PRICE_NN C PRICE IS NOT NULL

6 rows selected.

Page 154: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �! ����� ���������

8. Create a report titled Customer History Report. This report will contain eachcustomer’s history of renting videos. Be sure to include the customer name,movie rented, dates of the rentals, and duration of rentals. Count up the totalnumber of rentals for all customers for the reporting period. Save the script in afile named p17q8.sql.

SET ECHO OFFSET PAGESIZE 30 SET LINESIZE 52TTITLE ’Customer History Report’COLUMN member FORMAT A17COLUMN title FORMAT A15 WORD_WRAPPEDCOLUMN book_date FORMAT A9COLUMN duration FORMAT 9999999BREAK ON member skip 1 ON REPORTCOMPUTE COUNT LABEL ’Total Rentals’ OF - title ON REPORTSELECT m.first_name||’ ’||m.last_name MEMBER, t.title, r.book_date, r.act_ret_date - book_date DURATIONFROM member m, title t, rental rWHERE r.member_id = m.member_idAND r.title_id = t.title_idORDER BY m.last_name/CLEAR COMPUTECLEAR BREAKCOLUMN duration CLEARCOLUMN book_date CLEARCOLUMN title CLEARCOLUMN member CLEARSET PAGESIZE 25SET LINESIZE 80SET ECHO ON

Page 155: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �! ����� ���������

8.—continued

Sat Feb 10 page 1 Customer History Report

MEMBER TITLE BOOK_DATE DURATION----------------- --------------- --------- --------LaDoris Ngao My Day Off 08-FEB-96 Molly Urguhart Soda Gang 06-FEB-96 2 Carmen Velasquez Willie and 07-FEB-96 1 Christmas Too Interstellar 10-FEB-96 Wars Alien Again 09-FEB-96 ***************** --------------- Total Rentals 5

Page 156: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� �����������

�������� �# �����

1. Load and execute a loop counter.

a. Launch Procedure Builder. Your instructor will give you the logininformation.

b. From the menu, load the LABS\p19loop.pls file.c. Execute the procedure from the Interpreter pane. Pass a numeric value into the

procedure as demonstrated below.

Reminder: The Cue Cards can help you get started.

PL/SQL> count_loops(4);

� Solution file: SOLN\ p19q1.pls

PROCEDURE count_loops (v_count IN NUMBER)ISBEGIN FOR i in 1..v_count LOOP TEXT_IO.PUT_LINE (’Times through loop:’||TO_CHAR(i)); END LOOP;END;

2. Create, compile, and execute a procedure.a. Create a procedure named MY_MESSAGE as demonstrated below.

� Solution file: SOLN\ p19q2.pls

PROCEDURE my_message ISBEGIN TEXT_IO.PUT_LINE (’Hello World’);END;

b. Compile the procedure using the Program Unit Editor.

c. Execute the procedure from the Interpreter pane.

PL/SQL> my_message;

Page 157: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� �����

�������� �$ �����

1. A procedure can act as a function.True / False

� True

2. A procedure can be used in a SQL statement.True / False

� False

3. The IN OUT argument mode is the default mode.True / False

� False

4. Functions are executed as part of an expression.True / False

� True

5. Name the four parts of the subprogram syntax.

a. Header

b. Declarative

c. Executable

d. Exception handling

Page 158: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������

�������� �$ ����� ���������

6. Create a procedure called MY_PROCEDURE to output the phrase “MyProcedure Works” at the Interpreter prompt.

� Solution file: SOLN\ p20q6.pls

a. Replace the skeleton text with text from LABS\p20proc.pls.

� Click the Subprograms node in the Navigator. Click the Create button.In the dialog box, enter the name my_procedure. Click theProcedure radio button. Click OK.

� In the Program Unit Editor window, select all the skeleton text. Fromthe menu, select Edit/Import. Choose the LABS\p20proc.pls file. ClickOK.

PROCEDURE my_procedure IS TEXT_IO.PUTLINE (My Procedure Works)END;

Page 159: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����!

�������� �$ ����� ���������

6.—continued

b. Compile the code. Make appropriate corrections so code successfullycompiles.

� Corrections:

� Correct function name: TEXT_IO.PUT_LINE

� Add BEGIN after IS.

� Add quotation marks around text string: ’My Procedure Works’

� Add a semicolon after the output statement.

c. Execute the procedure at the Interpreter prompt.

PL/SQL> my_procedure;

My Procedure Works

Page 160: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ����������"

�������� �� �����

1. Evaluate each of the following declarations. Determine which of them are notlegal and explain why.

DECLARE v_id NUMBER (4);

a. Legal

DECLARE v_x, v_y, v_z VARCHAR2(10);

b. Illegal because only one identifier per declaration is allowed.

DECLARE v_birthdate DATE NOT NULL;

c. Illegal because the NOT NULL variable must be initialized.

DECLARE v_in_stock BOOLEAN := 1;

d. Illegal because 1 is not a ‘Boolean expression.

DECLARE emp_record emp_record_type;

e. Illegal because EMP_RECORD_TYPE must be declared.

DECLARE TYPE name_table_type IS TABLE OF VARCHAR2(20) INDEX BY BINARY_INTEGER; dept_name_table name_table_type;

f. Legal

Page 161: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ����#

�������� �� ����� ���������

2. Suppose you embed a sub-block within a block, as depicted below. You declaretwo variables, V_CUSTOMER and V_CREDIT_RATING, within the main block.You also declare two variables,V_CUSTOMER and V_NAME in the sub-block.Determine the values for each variable in each case listed below.

a. The value of V_CUSTOMER in the sub-block is

� “201” and the datatype is NUMBER.

b. The value of V_NAME in the sub-block is

� “Unisports”.

c. The value of V_CREDIT_RATING in the sub-block is

� “EXCELLENT”.

d. The value of V_CUSTOMER in the main block is

� “Womansport” and the datatype is VARCHAR2.

e. The value of V_NAME in the main block is

� V_NAME is not visible in the main block and you would see an error.

f. The value of V_CREDIT_RATING within the main block is

� “EXCELLENT”.

��%� &'�(%�

DECLARE v_customer NUMBER (7) := 201;

v_name VARCHAR2(25):= ’Unisports’;

�����

v_customer v_name v_credit_rating

����

DECLARE

v_customer VARCHAR2(50) := ’Womansport’;

v_credit_rating VARCHAR2(10) := ’EXCELLENT’;

BEGIN

SUB-BLOCK

v_customer v_name v_credit_rating

END;

Page 162: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������� $

�������� �� ����� ���������

3. Create and execute a procedure named MULTIPLIER that accepts two numbersthrough variables. The first number should be divided by the second number andhave the second number added to the result. The result should be written to aPL/SQL variable and printed to the screen.

� Solution file: SOLN\p21q3.pls

PROCEDURE multiplier (v_num1 IN NUMBER, v_num2 IN NUMBER)IS v_result NUMBER(9,2);BEGIN v_result := (v_num1/v_num2) + v_num2; TEXT_IO.PUT_LINE(TO_CHAR(v_result));END multiplier;

� Test the procedure.

PL/SQL> multiplier(2,4);

4.5

Page 163: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��� �

�������� �� ����� ���������

4. Build a function named ANN_COMP that computes the total compensation forone year. The annual salary and the annual bonus percentage will be passed to thefunction, and the bonus will need to be converted from a whole number to adecimal (for example, 15 to .15). If the salary is null, set it to zero beforecomputing the total compensation. Likewise, if the bonus is null, set it to zerobefore computing the total compensation. Execute the function. Reminder: Usethe NVL function to handle null values.

� Solution file: SOLN\p21q4.pls

FUNCTION ann_comp (v_salary IN NUMBER, v_bonus IN NUMBER)RETURN NUMBERIS v_total NUMBER(9,2);BEGIN v_total := NVL(v_salary, 0) * (1 + NVL(v_bonus, 0) / 100); RETURN (v_total);END ann_comp;

� Create a variable to hold the result. Execute the function. Print the outputvariable value.

PL/SQL> .CREATE NUMBER g_comp PRECISION 10 SCALE 2PL/SQL> :g_comp := ann_comp (50000,10);PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:g_comp));

55000

Page 164: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������� �

�������� �� ����� ���������

5. Rewrite the MULTIPLIER procedure in Exercise 3 as a function named MULTI.Execute the function.

� Solution file: SOLN\p21q5.pls

FUNCTION multi (v_num1 IN NUMBER, v_num2 IN NUMBER)RETURN NUMBERIS v_result NUMBER(9,2);BEGIN v_result := (v_num1/v_num2) + v_num2; RETURN (v_result);END multi;

� Create a variable to hold the result. Execute the function. Print the outputvariable value.

PL/SQL> .CREATE NUMBER g_multi PRECISION 9 SCALE 2

PL/SQL> :g_multi := multi(2,4);

PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:g_multi));

4.5

Page 165: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��� �

�������� �� �����

If you are not already connected to the database, be sure to do so 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.

� Solution file: SOLN\p22q1.pls

PROCEDURE new_dept (v_dept_name IN VARCHAR2)ISBEGIN INSERT INTO s_dept(id, name, region_id) VALUES (s_dept_id.NEXTVAL, v_dept_name, NULL); COMMIT;END new_dept;

d. Execute the procedure.

PL/SQL> new_dept (’Health’);

e. Display the new department that you created.

PL/SQL> SELECT * +> FROM s_dept +> WHERE name = ’Health’;

ID NAME REGION_ID-------- ------------------------- --------- 51 Health

1 row selected.

Page 166: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������� �

�������� �� ����� ���������

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.

� Solution file: SOLN\p22q2.pls

PROCEDURE update_dept (v_dept_id NUMBER, v_region_name VARCHAR2)IS v_region_id s_region.id%TYPE;BEGIN SELECT id INTO v_region_id FROM s_region WHERE UPPER(name) = UPPER(v_region_name); UPDATE s_dept SET region_id = v_region_id WHERE id = v_dept_id; COMMIT;END update_dept;

d. Test the procedure. What happens if you enter a region name that does notexist?

PL/SQL> update_dept (51, ’Europe’);

� If the operator enters an invalid region name, the NO_DATA_FOUNDexception is raised.

Page 167: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��� �

�������� �� ����� ���������

2.—continued

e. Display the department number, region number, and region name for theupdated department.

PL/SQL> SELECT d.id, d.region_id, r.name +> FROM s_dept d, s_region r +> WHERE d.region_id = r.id +> AND d.id = 51;

ID REGION_ID NAME-------- --------- ------------------------- 51 5 Europe

1 row selected.

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.

� Solution file: SOLN\p22q3.pls

PROCEDURE delete_dept (v_dept_id IN NUMBER)IS v_result NUMBER(2);BEGIN DELETE FROM s_dept WHERE id = v_dept_id; v_result := SQL%ROWCOUNT; TEXT_IO.PUT_LINE (TO_CHAR(v_result)||

’ row(s) deleted.’); COMMIT;END delete_dept;

Page 168: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������

�������� �� ����� ���������

3.—continued

c. Test the procedure. What happens if you enter a department number that doesnot exist?

PL/SQL> delete_dept (51);

� If the operator enters a department number that does not exist, theprocedure completes successfully because this does not constitute anexception.

What happens if you enter a department that has employees?

� The Oracle7 Server sends an error message that an integrity constrainthas been violated.

d. Confirm that the department has been deleted.

PL/SQL> SELECT * +> FROM s_dept +> WHERE id = 51;

No rows selected.

e. Test the procedure.

PL/SQL> delete_dept (51);

Page 169: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��� !

�������� �� ����� ���������

4. Create a procedure named NEW_EMP to insert a new employee into the S_EMPtable.

a. Create parameters for first name, last name, and job title.

b. Use the S_EMP_ID sequence generator for the employee number.

c. Compute the user ID by concatenating the first letter of the first name with thefirst seven letters of the last name, and converting all letters to lowercase.

d. Set the start date to the current date.

e. To determine the manager number, the department number, and the salary,first find the lowest-paid existing employee having the specified job title.Then, set these three values according to that existing employee. (If severalpeople are tied for lowest-paid, choose any one of them.)

f. Leave the comments and the commission percent empty.

� Solution file: SOLN\p22q4.pls

Code has been formatted to fit page.

Page 170: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ��������� "

�������� �� ����� ���������

4.—continued

PROCEDURE NEW_EMP (v_first_name IN s_emp.first_name%TYPE, v_last_name IN s_emp.last_name%TYPE, v_title IN s_emp.title%TYPE)IS v_userid s_emp.userid%TYPE; v_start_date s_emp.start_date%TYPE := SYSDATE; v_manager_id s_emp.manager_id%TYPE; v_dept_id s_emp.dept_id%TYPE; v_salary s_emp.salary%TYPE; v_existing_id s_emp.id%TYPE;BEGIN v_userid := LOWER (SUBSTR (v_first_name,1,1)|| SUBSTR (v_last_name,1,7)); SELECT MIN(id) INTO v_existing_id FROM s_emp WHERE title = v_title AND salary = (SELECT MIN(salary) FROM s_emp WHERE title = v_title); SELECT manager_id, dept_id, salary INTO v_manager_id, v_dept_id, v_salary FROM s_emp WHERE id = v_existing_id; INSERT INTO s_emp (id, last_name, first_name, userid, start_date, comments, manager_id, title, dept_id, salary, commission_pct) VALUES (s_emp_id.NEXTVAL, v_last_name, v_first_name, v_userid, v_start_date, NULL, v_manager_id, v_title, v_dept_id, v_salary, NULL); COMMIT;END new_emp;

Page 171: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ��� #

�������� �� ����� ���������

4.—continued

� Execute the procedure.

PL/SQL> new_emp (’Jayne’,’Bowman’, 2> ’Sales Representative’);

g. Verify the record has been added by viewing the employee’s number, userid,and salary.

PL/SQL> SELECT id, userid, salary 2> FROM s_emp 3> WHERE last_name = ’Bowman’;

ID USERID SALARY------ -------- ------------ 26 jbowman 1400.00

Page 172: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������!$

�������� �� �����

If you are not already connected to the database, be sure to do so now.

1. Create a procedure named SET_COMM to conditionally set the commissionpercentage for a given employee based upon total sales.

a. Prepare this exercise by disabling the constraint on the COMMISSION_PCTcolumn in the S_EMP table. You modify the commission percentage to valuesthat are not in the constraint.

PL/SQL> ALTER TABLE s_emp +> DROP CONSTRAINT s_emp_commission_pct_ck;

b. Create a parameter to accept the employee number from the user.

c. Find the sum of the totals for all orders placed by that employee.

d. If the sum is less than 100,000, set the commission percentage for theemployee to 10.

e. If the sum is between 100,000 and 1,000,000 inclusive, set the commissionpercentage for the employee to 15.

f. If the sum exceeds 1,000,000, set the commission percentage for theemployee to 20.

g. If no orders appear in the S_ORD table for the given employee, set thecommission percentage to 0.

h. Commit the change.

i. Test the block and view the changes. Results should appear for some exampleemployees as follows.

Employee Number Total Sales Resulting Commission

1 0 0

11 1,629,066.37 20

12 100,184.00 15

14 16,358.00 10

Page 173: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!�

�������� �� ����� ���������

1.—continued

� Solution file: SOLN\p23q1.pls

� In the Navigator, create a new procedure. Name it SET_COMM.

PROCEDURE set_comm (v_id IN NUMBER) IS v_sum_total NUMBER(11,2); v_comm s_emp.commission_pct%TYPE;BEGIN SELECT SUM(total) INTO v_sum_total FROM s_ord WHERE sales_rep_id = v_id; IF v_sum_total < 100000 THEN v_comm := 10; ELSIF v_sum_total <= 1000000 THEN v_comm := 15; ELSIF v_sum_total > 1000000 THEN v_comm := 20; ELSE v_comm := 0; END IF; UPDATE s_emp SET commission_pct = v_comm WHERE id = v_id; COMMIT;END set_comm;

Page 174: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������!�

�������� �� ����� ���������

1.—continued

Test the procedure.

PL/SQL> set_comm (1);

PL/SQL> set_comm (11);

PL/SQL> set_comm (12);

PL/SQL> set_comm (14);

PL/SQL> SELECT id, commission_pct +> FROM s_emp +> WHERE id IN (1, 11, 12, 14);

ID COMMISSION_PCT-------- ------------- 1 0.00 11 20.00 12 15.00 14 10.00

4 row selected.

2. Write a procedure named CUST_UPDATE that loops through the region numbers(1 through 5) to update the credit rating of all customers. Do not issue a commit.

a. If the region number is even, then set the credit rating to Excellent (even if thecustomer’s credit rating is already Excellent), otherwise set the credit rating toGood.

b. Once the rows are updated, find out how many rows were updated. Print thefollowing statements to the screen based on the number of rows updated.

i. If less than three rows updated, statement should read “Fewer than 3customer records updated for region number X”, where X represents theregion number.

ii. Otherwise, it should read “Y rows updated for region number X”, where Yis the number of rows updated, and X is the region number.

Page 175: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!�

�������� �� ����� ���������

2.—continued

� Solution: SOLN\p23q2.pls

� In the Navigator, create a new procedure. Name it CUST_UPDATE.

PROCEDURE cust_update IS v_output VARCHAR2(100); v_updated NUMBER(2); v_rating VARCHAR2(25); c_few CONSTANT VARCHAR2(100) := ’Fewer than 3 customer records updated forregion number ’;BEGIN FOR i IN 1..5 LOOP IF MOD(i,2) = 0 THEN v_rating := ’EXCELLENT’; ELSE v_rating := ’GOOD’; END IF; UPDATE s_customer SET credit_rating = v_rating WHERE region_id = i; v_updated := SQL%ROWCOUNT; IF v_updated < 3 THEN v_output := c_few || TO_CHAR(i); ELSE v_output := TO_CHAR (v_updated) || ’ rows updated for region number’||TO_CHAR(i); END IF; TEXT_IO.PUT_LINE (v_output); END LOOP;END cust_update;

� Execute the procedure by entering cust_update; at the Interpreterprompt. Observe the resulting statements.

Page 176: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������!�

�������� �� ����� ���������

2.—continued

c. Rollback the changes. Set a breakpoint on the conditional test for the numberof rows updated. Execute the procedure. Check the Stack node to verify thevalues of the variables as you Step Into the statements in the loop.

Reminder: You can use the Quick Tour, “Debugging a Program Unit” sectionfor assistance.

� Issue a ROLLBACK statement to undo changes. In the Navigator, clickthe CUST_UPDATE program unit. In the Interpreter source pane,double-click the line with the statement IF v_updated < 3 THENto set the breakpoint.

� Execute the procedure again. When the breakpoint is reached,investigate the values in the Stack node of the Navigator as you stepinto the code.

3. Create a procedure named EMP_MESSAGE that selects the employee last name,start date, and salary based on an employee number provided at execution. Print amessage to the screen based on any combination of one of the following criteria.Test employee numbers 2, 5, 16, 17, and 18. Hint: A nested IF is required.

Criteria Message

Salary greater than 1200 Salary more than 1200

Last name contains “r” Name contains “R”

Start date is in March March start date

None of the above **None**

� Solution file: SOLN\p23q3.pls

� In the Navigator, create a new procedure. Name it EMP_MESSAGE.

Page 177: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!�

�������� �� ����� ���������

3.—continued

PROCEDURE emp_message (v_emp_id IN NUMBER) IS v_last_name s_emp.last_name%TYPE; v_start_date s_emp.start_date%TYPE; v_salary s_emp.salary%TYPE; v_output VARCHAR2(100); c_name CONSTANT VARCHAR2(30) := ’Name contains ”R”’; c_date CONSTANT VARCHAR2(30) := ’March start date’; c_sal CONSTANT VARCHAR2(30) := ’Salary more than 1200’;BEGIN SELECT last_name, start_date, salary INTO v_last_name, v_start_date, v_salary FROM s_emp WHERE id = v_emp_id; IF v_salary > 1200 THEN v_output := c_sal; IF LOWER(v_last_name) LIKE ’%r%’ THEN v_output := v_output || ’ - ’ || c_name; IF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN IF v_output IS NULL THEN v_output := c_date; ELSE v_output := v_output || ’ - ’ || c_date; END IF; END IF; ELSIF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN v_output := v_output || ’ - ’ || c_date; END IF; ELSIF LOWER(v_last_name) LIKE ’%r%’ THEN v_output := c_name; IF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN v_output := v_output || ’ - ’ || c_date; END IF; ELSIF TO_CHAR(v_start_date, ’MON’) LIKE ’MAR’ THEN v_output := c_date; ELSE v_output := ’**None**’; END IF; TEXT_IO.PUT_LINE (v_output);END emp_message;

Page 178: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������!

�������� �� ����� ���������

3.—continued

� Test the procedure.

PL/SQL> emp_message (2);

Salary more than 1200 - March start date

PL/SQL> emp_message (5);

Salary more than 1200 - Name contains ”R” - Marchstart date

PL/SQL> emp_message (16);

Salary more than 1200 - Name contains ”R”

PL/SQL> emp_message (17);

March start date

PL/SQL> emp_message (18);

**None**

Page 179: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!!

�������� �� �����

1. Create a procedure named TOP_DOGS1 that determines the top employees withrespect to salaries.

a. Prepare for this exercise by creating a new table for storing employees andtheir salaries.

PL/SQL> CREATE TABLE top_dogs +> (name VARCHAR2(25), +> salary NUMBER(11,2));

b. Add a parameter to accept the user input n for the top number of employees.

c. Write a cursor FOR loop to get the last names and salaries of the top n people,with respect to salary, from the S_EMP table.

d. Store the names and salaries in the TOP_DOGS table.

e. Assume for the moment that no two employees have the same salary.

f. Test the exercise under a variety of special cases, such as n = 0, n is greaterthan the number of employees in the S_EMP table.

g. Empty the TOP_DOGS table after each test.

Page 180: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������!"

�������� �� ����� ���������

1.—continued

� Solution file: SOLN\p24q1.pls

� From the Tools menu, select Stored Program Unit Editor... Set the Owner toyour username, and click the New button. Create a new procedure. Name itTOP_DOGS1.

PROCEDURE top_dogs1 (v_n IN NUMBER)IS CURSOR emp_cursor IS SELECT last_name, salary FROM s_emp WHERE salary IS NOT NULL ORDER BY salary DESC;BEGIN DELETE FROM top_dogs; FOR emp_record IN emp_cursor LOOP EXIT WHEN emp_cursor%ROWCOUNT > v_n; INSERT INTO top_dogs (name, salary) VALUES (emp_record.last_name, emp_record.salary); END LOOP; COMMIT;END;

� Execute the procedure, and confirm the selection.

PL/SQL> top_dogs1(4);

PL/SQL> SELECT * FROM top_dogs;

NAME SALARY------------------------- ----------Velasquez 2500.00Ropeburn 1550.00Nguyen 1525.00Sedeghi 1515.00

4 rows selected.

Page 181: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���!#

�������� �� ����� ���������

1.—continued

� Execute the procedure with 0 as the parameter, and confirm the selection.

PL/SQL> top_dogs1(0);

PL/SQL> SELECT * FROM top_dogs;

NAME SALARY------------------------- ----------

No rows selected.

Page 182: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"$

�������� �� ����� ���������

1.—continued

� Execute the procedure with 30 as the parameter, and confirm the selection.

PL/SQL> top_dogs1(30);

PL/SQL> SELECT * FROM top_dogs;

NAME SALARY------------------------- ----------Velasquez 2500.00Ropeburn 1550.00Nguyen 1525.00Sedeghi 1515.00Giljum 1490.00Ngao 1450.00Dumas 1450.00Quick-To-See 1450.00Nagayama 1400.00Bowman 1400.00Magee 1400.00Maduro 1400.00Havel 1307.00Catchpole 1300.00Menchu 1250.00Urguhart 1200.00Nozaki 1200.00Biri 1100.00Schwartz 1100.00Smith 940.00Dancs 860.00Markarian 850.00Chang 800.00Patel 795.00Patel 795.00Newman 750.00

26 rows selected.

Page 183: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���"�

�������� �� ����� ���������

2. Create a stored procedure named ADD_STARS to reward all employees byappending an asterisk in the STARS column for every commission point.

a. Prepare for this exercise by creating a new column in the S_EMP table forstoring asterisks (*).

PL/SQL> ALTER TABLE s_emp +> ADD stars VARCHAR2(100);

b. Determine the commission percentage for the employee, rounded to thenearest whole number. Also, consider the case where the employee has nocommission percent.

c. Add an asterisk to a string of asterisks for every commission point. Forexample, if the employee has a commission percentage of 10, then the STARScolumn will contain ten asterisks.

d. Update the STARS column for each employee with the string of asterisks.

Page 184: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"�

�������� �� ����� ���������

2.—continued

� Solution file: SOLN\p24q2.pls

� From the Tools menu, select Stored Program Unit Editor... Set the Owner toyour username, and click the New button. Create a new procedure. Name itADD_STARS.

PROCEDURE add_stars IS v_stars s_emp.stars%TYPE := NULL; CURSOR emp_cursor IS SELECT id, NVL(ROUND(commission_pct),0) comm FROM s_emp FOR UPDATE;BEGIN FOR emp_record IN emp_cursor LOOP BEGIN FOR i IN 1..emp_record.comm LOOP v_stars := v_stars || ’*’; END LOOP; UPDATE s_emp SET stars = v_stars WHERE CURRENT OF emp_cursor; v_stars := NULL; END; END LOOP; COMMIT;END;

Page 185: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���"�

�������� �� ����� ���������

2.—continued

� Execute the procedure to put in the stars, and confirm the changes to thetable.

PL/SQL> add_stars;PL/SQL> SELECT id, commission_pct, stars +> FROM s_emp +> WHERE commission_pct IS NOT NULL;

ID COMMISSION_PCT STARS-------- -------------- ---------------------------- 1 0.00 11 20.00 ******************** 12 15.00 *************** 13 10.00 ********** 14 10.00 ********** 15 17.50 ******************

6 rows selected.

3. Copy the TOP_DOGS1 procedure from exercise 1, and name it TOP_DOGS2.Modify the TOP_DOGS2 procedure to consider the case where severalemployees in the exercise 1 have the same salary. For each name listed, all nameshaving the same salary should also be listed.

Execute the TOP_DOGS2 procedure. Enter 6, 7, or 8 for n, then Ngao, Dumas,and Quick-To-See should all display. If you enter 9, 10, or 11 for n, thenNagayama, Magee, and Maduro should all display.

Remember to empty the TOP_DOGS table after each test.

Page 186: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"�

�������� �� ����� ���������

3.—continued

� Solution file: SOLN\p24q3.pls

� In the Navigator, select the TOP_DOGS1 procedure. From the menu, chooseEdit—>Duplicate. Open the copy of TOP_DOGS1_XXX, where XXXrepresents an internal number created by Procedure Builder.

PROCEDURE top_dogs2 (v_n IN NUMBER)IS v_last_salary s_emp.salary%TYPE := -1; -- salary never negative CURSOR emp_cursor IS SELECT last_name, salary FROM s_emp WHERE salary IS NOT NULL ORDER BY salary DESC; emp_record emp_cursor%ROWTYPE;BEGIN DELETE FROM top_dogs; OPEN emp_cursor; FETCH emp_cursor INTO emp_record; WHILE (emp_cursor%ROWCOUNT <= v_n OR emp_record.salary = v_last_salary) AND emp_cursor%FOUND LOOP INSERT INTO top_dogs (name, salary) VALUES (emp_record.last_name,emp_record.salary); v_last_salary := emp_record.salary; FETCH emp_cursor INTO emp_record; END LOOP; CLOSE emp_cursor; COMMIT;END;

Page 187: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���"�

�������� �� ����� ���������

3.—continued

� Execute the procedure.

PL/SQL> top_dogs2(7);PL/SQL> SELECT * FROM top_dogs;

NAME SALARY-------------------- -------------Velasquez 2500.00Ropeburn 1550.00Nguyen 1525.00Sedeghi 1515.00Giljum 1490.00Ngao 1450.00Dumas 1450.00Quick-To-See 1450.00

8 rows selected.

PL/SQL> top_dogs2(10);PL/SQL> SELECT * FROM top_dogs;

NAME SALARY-------------------- -------------Velasquez 2500.00Ropeburn 1550.00Nguyen 1525.00Sedeghi 1515.00Giljum 1490.00Ngao 1450.00Dumas 1450.00Quick-To-See 1450.00Nagayama 1400.00Bowman 1400.00Magee 1400.00Maduro 1400.00

12 rows selected.

Page 188: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������"

�������� �� �����

1. Modify the procedure to handle exceptions. The procedure tries to update regionnumbers for existing departments.

a. Load the LABS\p25q1a.pls script file. Note: The procedure UPDATE_DEPT2is loaded and compiled.

� From the menu, select File/Load. Select the file LABS\p25q1a.pls.

b. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (50,’US’);

PL/SQL> update_dept2 (50,’US’);

ERROR 0 at line 6, column 0 Unhandled exception ORA-01401: no data found which was raised in a statement starting at line 6 of UPDATE_DEPT2

c. Write an exception handler for the error to pass a message to the user that thespecified region does not exist.

d. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (31,’Asia’);

e. Write an exception handler for the error to pass a message to the user that thespecified region already has a department of that name.

f. Execute the procedure by entering the following text.

PL/SQL> update_dept2 (99,’Europe’);

g. Write an exception handler for the error to pass a message to the user that thespecified department number does not exist.

Reminder: The SQL attribute %NOTFOUND and raise an exceptionmanually.

Page 189: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���"!

�������� �� ����� ���������

1.—continued

� Solution file: SOLN\p25q1.pls

� In the Program Unit editor, modify the procedure named UPDATE_DEPT2.Add the text you see in bold.

PROCEDURE update_dept2 (v_dept_id IN NUMBER, v_region_name IN VARCHAR2)IS v_region_id s_region.id%TYPE; dept_record s_dept%ROWTYPE; e_count EXCEPTION;BEGIN SELECT id INTO v_region_id FROM s_region WHERE UPPER(name) = UPPER(v_region_name); UPDATE s_dept SET region_id = v_region_id WHERE id = v_dept_id; IF SQL%NOTFOUND THEN RAISE e_count; END IF; COMMIT;EXCEPTION WHEN NO_DATA_FOUND THEN ROLLBACK; TEXT_IO.PUT_LINE (v_region_name|| ’ region does not exist.’); WHEN DUP_VAL_ON_INDEX THEN ROLLBACK; TEXT_IO.PUT_LINE (v_region_name|| ’ already has a department of that name.’); WHEN e_count THEN ROLLBACK; TEXT_IO.PUT_LINE (’Department number ’|| TO_CHAR(v_dept_id)||’ does not exist.’);END update_dept2;

Page 190: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������""

�������� �� ����� ���������

1.—continued

� Execute the subprogram.

PL/SQL> update_dept (50,’US’);

US region does not exist.

PL/SQL> update_dept (31,’Asia’);

Asia already has a department of that name.

PL/SQL> update_dept (99,’Europe’);

Department number 99 does not exist.

Page 191: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���"#

�������� �� ����� ���������

2. Write a procedure named SALARY_RANGE that prints the names of theemployees that make plus or minus 100 dollars of the salary value entered.

a. If there is no employee within that salary range, then print a message to theuser indicating that is the case. Use an exception for this case.

b. If there are more than 3 employees within that range, then the message shouldindicate how many employees have that salary range.

Your results should look like the list below. Results have been formatted to fitthe page.

PL/SQL> SALARY_RANGE (1000);

Employees who make around $1000 are: Biri, Schwartz, Smith

PL/SQL> SALARY_RANGE (900);

4 employoee salaries are within $100 of $900

PL/SQL> SALARY_RANGE (2000);

No records within the $2000 range.

� Solution file: SOLN\p25q2.pls

� In the Navigator, create a new procedure. Name it SALARY_RANGE.

Page 192: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������#$

�������� �� ����� ���������

2.—continued

PROCEDURE salary_range (v_salary IN s_emp.salary%TYPE)IS v_count INTEGER := 0; v_flag BOOLEAN := FALSE; v_name VARCHAR2(255); v_emp_name s_emp.last_name%TYPE; v_emp_sal s_emp.salary%TYPE; CURSOR emp_cursor IS SELECT last_name, salary FROM s_emp WHERE salary BETWEEN (v_salary - 100) AND (v_salary + 100) ORDER BY last_name DESC; e_no_emp exception; v_code NUMBER(6); v_msg VARCHAR2(255);BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO v_emp_name, v_emp_sal; EXIT WHEN emp_cursor%NOTFOUND; IF v_flag THEN v_count := v_count + 1; ELSE IF v_name IS NULL THEN v_name := v_emp_name; ELSE v_name := v_emp_name||’, ’||v_name; END IF; v_count := v_count + 1; IF v_count > 3 THEN v_flag := TRUE; END IF; END IF; END LOOP;

� Code continues on next page.

Page 193: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#�

�������� �� ����� ���������

2.—continued

IF v_name IS NULL THEN RAISE e_no_emp; ELSIF v_flag THEN TEXT_IO.PUT_LINE (TO_CHAR(v_count) ||’ employee salaries are within $100 of $’ ||TO_CHAR(v_salary)); ELSE TEXT_IO.PUT_LINE (’Employees who make around $’ ||TO_CHAR(v_salary)||’ are: ’||v_name); END IF;EXCEPTION WHEN e_no_emp THEN TEXT_IO.PUT_LINE (’No records within the $’ ||TO_CHAR(v_salary)||’ range.’); WHEN OTHERS THEN v_code := SQLCODE; v_msg := SQLERRM; TEXT_IO.PUT_LINE (TO_CHAR(v_code)||’: ’||v_msg);END salary_range;

� Execute the procedure.Output has been formatted to fit the page.

PL/SQL> SALARY_RANGE (1000);

Employees who make around $1000 are: Biri, Schwartz, Smith

PL/SQL> SALARY_RANGE (900);

4 employoee salaries are within $100 of $900

PL/SQL> SALARY_RANGE (2000);

No records within the $2000 range.

Page 194: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������#�

�������� � �����

1. Complete the database design by writing subprograms to perform the followingactions.

a. Create a function named NEW_MEMBER to return the membership numberfor that new member. Be sure to use a sequence generator to create the uniquemember numbers. Check the data dictionary for the sequence name.

� Solution file: SOLN\p26q1a.pls

Code has been formatted to fit page.

FUNCTION new_member (v_first_name IN member.first_name%TYPE, v_last_name IN member.last_name%TYPE, v_address IN member.address%TYPE, v_city IN member.city%TYPE, v_phone IN member.phone%TYPE)RETURN number IS v_member_id member.member_id%TYPE;BEGIN INSERT INTO member(member_id, last_name, first_name, address, city, phone, join_date) VALUES (member_id_seq.NEXTVAL, v_last_name, v_first_name, v_address, v_city, v_phone, SYSDATE); COMMIT; SELECT member_id_seq.CURRVAL INTO v_member_id FROM dual; RETURN (v_member_id);END;

Page 195: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#�

�������� � ����� ���������

1.—continued

b. Create a function named NEW_RENTAL to record a new rental based on amember’s last name. Return a message with the expected due date. If two ormore people have the same last name, store the first name, last name, phone,and membership number for all matching last names in the RESULTS table.

� Solution file: SOLN\p26q1b.pls

Code has been formatted to fit page.

FUNCTION new_rental (v_last_name IN member.last_name%TYPE, v_copy_id IN title_copy.copy_id%TYPE, v_title_id IN title_copy.title_id%TYPE)RETURN VARCHAR2 IS v_status title_copy.status%TYPE := ’RENTED’; v_member_id member.member_id%TYPE; v_message results.message%TYPE;BEGIN DELETE FROM results; SELECT member_id INTO v_member_id FROM member WHERE UPPER(last_name) = UPPER(v_last_name); INSERT INTO rental (book_date, copy_id, member_id, title_id, act_ret_date, exp_ret_date) VALUES (sysdate, v_copy_id, v_member_id, v_title_id, NULL, sysdate+2); UPDATE title_copy SET status = v_status WHERE copy_id = v_copy_id AND title_id = v_title_id; COMMIT; v_message := ’This video is due: ’|| TO_CHAR(sysdate+2,’DD-MON-YY’); RETURN (v_message);

Code continued on next page.

Page 196: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������#�

�������� � ����� ���������

1b.—continued

Code has been formatted to fit page.

EXCEPTION WHEN TOO_MANY_ROWS THEN -- More than one member with the given last name. DECLARE CURSOR member_cursor IS SELECT first_name, last_name, phone, member_id FROM member WHERE UPPER(last_name) = UPPER(v_last_name); BEGIN FOR member_rec IN member_cursor LOOP INSERT INTO results (member_id, first_name, last_name, phone) VALUES (member_rec.member_id, member_rec.first_name, member_rec.last_name, member_rec.phone); END LOOP; COMMIT; v_message := ’More than one ’||v_last_name|| ’. Please check RESULTS table.’; RETURN (v_message); END; WHEN NO_DATA_FOUND THEN --No members with the given last name v_message := v_last_name|| ’ is not a registered member.’; RETURN (v_message);END;

Page 197: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#�

�������� � ����� ���������

1.—continued

c. Create a procedure named MEM_TITLES to retrieve all the titles rented by amember. Store the results in the RESULTS table.

� Solution file: SOLN\p26q1c.pls

PROCEDURE mem_titles (v_mem_id member.member_id%TYPE)IS CURSOR member_cursor IS SELECT r.member_id, t.title, r.title_id FROM rental r, title t WHERE r.member_id = v_mem_id AND r.title_id = t.title_id;BEGIN DELETE FROM results; FOR member_record IN member_cursor LOOP INSERT INTO results (member_id, title_id, title) VALUES (member_record.member_id, member_record.title_id, member_record.title); END LOOP; COMMIT;END;

Page 198: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������#

�������� � ����� ���������

1.—continued

d. If a title is rented, create a reservation for that movie. Name your procedureRESERVE_MOVIE.

� Solution file: SOLN\p26q1d.pls

Code has been formatted to fit page.

PROCEDURE reserve_movie (v_member_id IN member.member_id%TYPE, v_title IN title.title%TYPE)IS v_title_id title.title_id%TYPE; v_message results.message%TYPE; v_exp_ret_date rental.exp_ret_date%TYPE;BEGIN DELETE FROM results; SELECT title_id INTO v_title_id FROM title WHERE UPPER(title) = UPPER (v_title); INSERT INTO reservation (res_date,member_id,title_id) VALUES (sysdate,v_member_id,v_title_id); SELECT MIN(exp_ret_date) INTO v_exp_ret_date FROM rental WHERE title_id = v_title_id; v_message := ’Earliest expected return date: ’|| TO_CHAR(v_exp_ret_date,’DD-MON-YY’); INSERT INTO results (title_id, title, message) VALUES (v_title_id, v_title, v_message); COMMIT;END;

Page 199: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���#!

�������� � ����� ���������

1.—continued

e. When a video is returned, change the rental status for that returned copy.When the video is successfully checked in, store a message in the RESULTStable. Check the to see if there are reservations for the film title, and store amessage in the RESULTS table. Name your procedure RETURN_RENTAL.

� Solution file: SOLN\p26q1e.pls

Code has been formatted to fit page.

PROCEDURE return_rental (v_copy_id IN rental.copy_id%TYPE, v_title_id IN rental.title_id%TYPE)IS v_message results.message%TYPE; v_status title_copy.status%TYPE := ’AVAILABLE’; v_res_date reservation.res_date%TYPE; v_member_id reservation.member_id%TYPE; e_look_up_failed EXCEPTION;BEGIN DELETE FROM results; UPDATE rental SET act_ret_date = SYSDATE WHERE copy_id = v_copy_id AND title_id = v_title_id; IF SQL%NOTFOUND THEN RAISE e_look_up_failed; END IF; SELECT MIN(res_date), member_id INTO v_res_date, v_member_id FROM reservation WHERE title_id = v_title_id GROUP BY member_id; v_status := ’RESERVED’; v_message := ’Call this member to say the movie has been returned.’;

Code continued on next page.

Page 200: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������#"

�������� � ����� ���������

1e.—continued

Code has been formatted to fit page.

INSERT INTO results (member_id, title_id, message) VALUES (v_member_id, v_title_id, v_message); UPDATE title_copy SET status = v_status WHERE copy_id = v_copy_id AND title_id = v_title_id; COMMIT;EXCEPTION WHEN NO_DATA_FOUND THEN UPDATE title_copy SET status = v_status WHERE copy_id = v_copy_id AND title_id = v_title_id; COMMIT; WHEN e_look_up_failed THEN v_message := ’Invalid COPY_ID=’|| TO_CHAR(v_copy_id)|| ’ and TITLE_ID=’||TO_CHAR(v_title_id)|| ’ combination.’; INSERT INTO results (message) VALUES (v_message); COMMIT;END;

Page 201: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���##

�������� � ����� ���������

1.—continued

f. If a video is returned damaged, change its status to DAMAGED. If that copywas the only copy owned by the store, store a message to buy another copy inthe RESULTS table. If only one copy remains for rental, store a warning thatonly one copy is left for rental in the RESULTS table. Name your procedureDAMAGED_COPY.

� Solution file: SOLN\p26q1f.pls

PROCEDURE damaged_copy (v_copy_id IN title_copy.copy_id%TYPE, v_title_id IN title_copy.title_id%TYPE)IS v_status title_copy.status%TYPE := ’DESTROYED’; v_count NUMBER; v_message results.message%TYPE := NULL;BEGIN DELETE FROM results; UPDATE title_copy SET status = v_status WHERE copy_id = v_copy_id AND title_id = v_title_id; UPDATE rental SET act_ret_date = SYSDATE WHERE copy_id = v_copy_id AND title_id = v_title_id; SELECT COUNT(title_id) INTO v_count FROM title_copy WHERE title_id = v_title_id; IF v_count = 1 THEN v_message := ’Buy another copy.’; INSERT INTO results (title_id, message) VALUES (v_title_id, v_message);

Code continued on next page.

Page 202: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$$

�������� � ����� ���������

1f.—continued

ELSIF v_count = 2 THEN v_message := ’Only one copy left for rental.’; INSERT INTO results (title_id, message) VALUES (v_title_id, v_message); END IF; COMMIT;END;

Page 203: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�������� ����� ���$�

�������� � ����� ���������

1.—continued

g. Create a procedure named TOP_RENTAL to determine the top rental. Allowfor more than one top rental. Store the names and a message of the top rentalsin the RESULTS table.

� Solution file: SOLN\p26q1g.pls

Code has been formatted to fit page.

PROCEDURE top_rental IS v_count_title NUMBER; v_title_id title.title_id%TYPE; v_title title.title%TYPE; v_flag NUMBER; v_message results.message%TYPE := ’Top rental’; CURSOR popular_cursor IS SELECT r.title_id, t.title, COUNT(r.title_id) FROM rental r, title t WHERE r.title_id = t.title_id GROUP BY r.title_id, t.title ORDER BY 3 DESC;BEGIN DELETE FROM results; OPEN popular_cursor; FETCH popular_cursor INTO v_title_id, v_title, v_count_title; v_flag := v_count_title; WHILE (popular_cursor%FOUND AND v_flag = v_count_title) LOOP INSERT INTO results (title_id, title, message) VALUES (v_title_id, v_title, v_message); FETCH popular_cursor INTO v_title_id, v_title, v_count_title; END LOOP; COMMIT; END;

Page 204: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������� � ������ ��� ��� ������ � ��� �������� ���������$�

Page 205: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ����

Page 206: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� ��������

Page 207: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ���

����� �� ��� �� �������� �����

�!��"#

�!�$%"$��&'

�!�&�

�!(����#"&

�!�"��

�!�#) "

�!�&���(�

�&�!����

�)�"�!&"�!��

�&���(�!��

(����#"&!��

�)�"�!&"�!��

�"��!��

�#) "!��

�&���(�!��

��

��

��

����

��

*

��

�!&" ��$

�!+)&",���"

��

��

&" ��$!��

&" ��$!��

#)$) "&!��

��

�!"#�

#)$) "&!��

��

��

* Unique occurrences are identified by PRODUCT_ID and WAREHOUSE_ID.

Page 208: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������-

�!(����#"& �����

SQL> DESCRIBE s_customer

Name Null? Type

ID NOT NULL NUMBER(7)

NAME NOT NULL VARCHAR2(50)

PHONE VARCHAR2(25)

ADDRESS VARCHAR2(400)

CITY VARCHAR2(30)

STATE VARCHAR2(20)

COUNTRY VARCHAR2(30)

ZIP_CODE VARCHAR2(75)

CREDIT_RATING VARCHAR2(9)

SALES_REP_ID NUMBER(7)

REGION_ID NUMBER(7)

COMMENTS VARCHAR2(255)

Note: The data on the pages to follow has been formatted. Use the provided tabledescriptions for accurate column names.

Page 209: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��.

�!(����#"& ����� ���������

SQL> SELECT * FROM s_customer;

Continued on Next Page

Page 210: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������/

�!(����#"& ����� ���������

Page 211: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��0

�!�"�� �����

SQL> DESCRIBE s_dept

Name Null? Type

ID NOT NULL NUMBER(7)

NAME NOT NULL VARCHAR2(25)

REGION_ID NUMBER(7)

SQL> SELECT * FROM s_dept;

Page 212: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������1

�!"#� �����

SQL> DESCRIBE s_emp

Name Null? Type

ID NOT NULL NUMBER(7)LAST_NAME NOT NULL VARCHAR2(25)FIRST_NAME VARCHAR2(25)USERID NOT NULL VARCHAR2(8)START_DATE DATECOMMENTS VARCHAR2(255)MANAGER_ID NUMBER(7)TITLE VARCHAR2(25)DEPT_ID NUMBER(7)SALARY NUMBER(11,2)COMMISSION_PCT NUMBER(4,2)

Page 213: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��2

�!"#� ����� ���������

SQL> SELECT * FROM s_emp;

Page 214: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������34

�!�#) " �����

SQL> DESCRIBE s_image

Name Null? Type

ID NOT NULL NUMBER(7)

FORMAT VARCHAR2(25)

USE_FILENAME VARCHAR2(25)

FILENAME VARCHAR2(25)

IMAGE LONG RAW

SQL> SELECT * FROM s_image;

Page 215: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��33

�!�$%"$��&' �����

SQL> DESCRIBE s_inventory

Name Null? Type

PRODUCT_ID NOT NULL NUMBER(7)WAREHOUSE_ID NOT NULL NUMBER(7)AMOUNT_IN_STOCK NUMBER(9)REORDER_POINT NUMBER(9)MAX_IN_STOCK NUMBER(9)OUT_OF_STOCK_EXPLANATION VARCHAR2(255)RESTOCK_DATE DATE

Page 216: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������3�

�!�$%"$��&' ����� ���������

SQL> SELECT * FROM s_inventory;

Continued on Next Page

Page 217: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��3�

�!�$%"$��&' ���������

Continued on Next Page

Page 218: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������3-

�!�$%"$��&' ���������

Continued on Next Page

Page 219: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��3.

�!�$%"$��&' ���������

Page 220: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������3/

�!��"# �����

SQL> DESCRIBE s_item

Name Null? Type

ORD_ID NOT NULL NUMBER(7)ITEM_ID NOT NULL NUMBER(7)PRODUCT_ID NOT NULL NUMBER(7)PRICE NUMBER(11,2)QUANTITY NUMBER(9)QUANTITY_SHIPPED NUMBER(9)

Page 221: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��30

�!��"# ����� ���������

SQL> SELECT * FROM s_item;

Continued on Next Page

Page 222: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� �������31

�!��"# ����� ���������

Continued on Next Page

Page 223: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ��32

�!��"# ����� ���������

Page 224: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� ��������4

�!�&� �����

SQL> DESCRIBE s_ord

Name Null? Type

ID NOT NULL NUMBER(7)

CUSTOMER_ID NOT NULL NUMBER(7)

DATE_ORDERED DATE

DATE_SHIPPED DATE

SALES_REP_ID NUMBER(7)

TOTAL NUMBER(11,2)

PAYMENT_TYPE VARCHAR2(6)

ORDER_FILLED VARCHAR2(1)

Page 225: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ���3

�!�&� ����� ���������

SQL> SELECT * FROM s_ord;

Page 226: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� ���������

�!�&���(� �����

SQL> DESCRIBE s_product

Name Null? Type

ID NOT NULL NUMBER(7)NAME NOT NULL VARCHAR2(50)SHORT_DESC VARCHAR2(255)LONGTEXT_ID NUMBER(7)

IMAGE_ID NUMBER(7)SUGGESTED_WHLSL_PRICE NUMBER(11,2)WHLSL_UNITS VARCHAR2(25)

Page 227: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ����

�!�&���(� ����� ���������

SQL> SELECT * FROM s_product;

Continued on Next Page

Page 228: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� ��������-

�!�&���(� ����� ���������

Page 229: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ �� ��� ���� ���.

�!&" ��$ �����

SQL> DESCRIBE s_region

Name Null? Type

ID NOT NULL NUMBER(7)

NAME NOT NULL VARCHAR2(50)

SQL> SELECT * FROM s_region;

Page 230: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��� ���� � � ������ ��� ��� ������ ���� � ����� ��������/

�!+)&",���" �����

SQL> DESCRIBE s_warehouse

Name Null? Type

ID NOT NULL NUMBER (7)

REGION_ID NOT NULL NUMBER (7)

ADDRESS LONG

CITY VARCHAR2 (30)

STATE VARCHAR2 (20)

COUNTRY VARCHAR2 (30)

ZIP_CODE VARCHAR2 (75)

PHONE VARCHAR2 (25)

MANAGER_ID NUMBER (7)

SQL> SELECT * FROM s_warehouse;

ID REGION_ID ADDRESS CITY STATE _____ ___________ _______________ ______________ _______

101 1 283 King Street SEATTLE WA10501 5 5 Modrany BRATISLAVA

201 2 68 Via Centrale SAO PAOLO301 3 6921 King Way LAGOS401 4 86 Chu Street HONG KONG

COUNTRY ZIP_CODE PHONE MANAGER_ID__________________ __________ _________ _____________USA 6CZECHOZLOVAKIA 10Brazil 7Nigeria 8

9

Note: Table has been split into two parts to make it fit in the page.

Page 231: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� �

����� � ��� ������ �����

����

Page 232: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������

Page 233: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���

� !�� �"��

This lesson covers formatting query output to produce simple reports,controlling the SQL*Plus environment, and manipulating PL/SQL code usingSQL*Plus.

At the end of this lesson, you should be able to

� Differentiate between SQL and SQL*Plus commands.

� Identify SET commands used to control the SQL*Plus environment.

� Customize reports using SQL*Plus formatting commands.

� Create and modify anonymous blocks and program units with SQL*Plus and theonline editor.

� Execute SQL*Plus commands, anonymous blocks, program units, and SQLstatements.

� Compile procedures and functions.

� Embed messages to assist with debugging code.

Page 234: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������#

$%� ������ &�"����'��

Page 235: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��(

�"��"��)

SQL*Plus is an environment in which you can

� Execute SQL statements to retrieve, modify, add, and remove data from databasetables.

� Format, perform calculations on, store, and print query results in the form ofreports.

� Issue SQL statements to create, alter, and remove database tables.

� Create anonymous blocks, subprograms, database triggers using procedurallanguage extension, PL/SQL.

SQL*Plus has a variety of commands you need to use to execute subprograms, passvalues in and out of PL/SQL blocks, and debug your code.

SQL*Plus commands may be divided into the following main categories.

Category Purpose

Environment Affects the general behavior of SQL statements for thesession.

Format Formats query results.

File manipulation Saves, loads, and runs script files.

Execution Sends SQL or PL/SQL commands from SQL buffer toOracle7 Server.

Edit Modifies SQL commands in the buffer.

Interaction Allows users to create and pass variables to SQLstatements, print variable values, and print messages tothe screen.

Miscellaneous Various commands to connect to the database,manipulate the SQL*Plus environment, and displaycolumn definitions.

Page 236: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������*

&� ����� ��''���� �� ������

Page 237: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��+

&� ����� ��''���� �� ������

Once you log in to SQL*Plus, you see the command prompt. Issue all yourcommands at this prompt. Three types of commands can be entered at this prompt.

� SQL commands to manipulate data and structures in the database.

� SQL*Plus command to format query results, set the environment, edit commands,and create variables.

� PL/SQL blocks to work with information in the database in a procedural method.

To execute commands, type them at the command prompt. SQL*Plus commands donot need to be terminated with a semicolon (;). SQL statements and PL/SQL blocksdo need to be terminated with a semicolon to send the statement to the Oracle7Server.

Page 238: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������,

Page 239: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��-

��'������� �. ��� ��� ������ ��''����

This table compares SQL and SQL*Plus commands. They are distinctly differentprograms, but are used together to perform some tasks, such as to format data in areport and to control command files.

SQL SQL*Plus

Is a language for communicating withthe Oracle Server to access data.

Recognizes SQL commands, and sendsthem to the server.

Is based on American NationalStandards Institute (ANSI) standardSQL.

Is the Oracle proprietary interface forexecuting SQL commands.

Manipulates data and table definitions inthe database.

Does not allow you to manipulate valuesin the database.

Is entered into the SQL*Buffer on one ormore lines.

Is entered one line at a time; not storedin the SQL buffer.

Does not have a continuation character. Has a dash “-” as a continuationcharacter if the command is longer thanone line.

Cannot be abbreviated. Can be abbreviated.

Uses a termination character to executecommands required.

Does not require termination characters;commands are immediately executed.

Uses functions to perform someformatting.

Uses commands to format data.

Page 240: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������/0

Page 241: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��//

������ �&$ ��''����

Control the environment in which SQL*Plus is currently operating by using the SETcommands.

�1� �2

SET system_variable value

where: system_variable is a variable that controls one aspect of thesession environment.

value is a value for the system variable.

3�.��� �� ���� ����� %� ��������� 4���

The login.sql file contains standard SET and other SQL*Plus commands that youmay require for every session. The file is read and commands are implemented at login. When you log out of your session, all customized setting are lost.

�%������ %� 3�.��� �� ����

The settings implemented by login.sql can be changed during the current session.Changes made are only current for that session. As soon as you log out, those settingsare lost.

Add permanent changes to settings to the login.sql file.

For more information, seeSQL*Plus User’s Guide and Reference, Release 3.3, “Command Reference.”

Page 242: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������/�

Page 243: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��/�

��� ��� �&$ ��''����

��'� ���.�� �&$ ��''����

SET Variable and Values Description

ARRAY[SIZE] {20|n} Sets the database data fetch size.

COLSEP { |text} Sets text to be printed between columns. Defaultis single space.

FEED[BACK] {6|n|OFF|ON} Displays the number of records returned by aquery when the query selects at least n records.

HEA[DING]{OFF|ON} Determine whether column headings aredisplayed in reports.

LIN[ESIZE] {80|n} Sets the number of characters per line to n forreports.

LONG {80|n} Sets maximum width for displaying LONGvalues.

PAGES[IZE] {24|n} Specifies the number of lines per page of output.

PAU[SE] {OFF|ON|text} Allows you to control scrolling of your terminal.You must press [Return] after seeing each pause.

TERM[OUT] {OFF|ON} Determines whether output is displayed to thescreen.

5���������

� Use the SHOW command to view current values for any of these settings, forexample SHOW PAUSE. To see all SET variable values, use the SHOW ALLcommand.

� The value n represents a numeric value.

� Underlined values shown above indicate default values. If you enter no value withthe variable, then SQL*Plus assumes the default value.

Page 244: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������/#

Page 245: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��/(

���� ��� � �����

����� 4���

You can create a script file (or command file) that includes both a SQL SELECTstatement and SQL*Plus commands used to format and reset command values. Scriptfiles are useful for saving both a SQL statement and any SQL*Plus settings specificto that statement.

Additionally, you can create a file to hold all your default SQL*Plus commands,which may be executed at any time to reset your settings. This file can be executedfrom within your command file.

������ 4��'� ��''����

You can control the report features described above by using the followingcommands:

Command Purpose

COL[UMN] [column option] Controls column formats.

TTI[TLE] [text|OFF|ON] Specifies a header to appear at the top of eachpage of the report.

BTI[TLE] [text|OFF|ON] Specifies a footer to appear at the bottom ofeach page of the report.

5���������

� All format commands remain in effect until the end of the SQL*Plus session, oruntil the format setting is overwritten or cleared.

� Remember to reset your SQL*Plus settings to default values after every report.

� There is no command for setting a SQL*Plus variable to its default value; youmust know the specific value or log out and log in again.

� If you give an alias to your column, you must reference the alias name, not thecolumn name.

Page 246: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������/*

Page 247: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��/+

���� ��� � ����� ������

$$�$�& ��� �$�$�& ��''����

Use the TTITLE command to format page headers and the BTITLE command forfooters. Footers appear at the end of the page according to the PAGESIZE value.

�1� �2

The syntax for BTITLE and TTITLE is identical. Only the TTITLE syntax is shown.You can use the vertical bar (|) to split the text of the title across several lines.

TTI[TLE] [printspec [text|variable]][OFF|ON]

where: printspec is an option to specify the type of settings.

text represents the title text. Enter single quotes ifthe text is more than one word.

variable is a system-maintained value.

&2�'���

Set the report header to display Salary centered on one line, and Report centeredbelow it.

SQL> TTITLE ’Salary|Report’

3�����1 �� ����� �� ����

To show or clear the current header and footer command settings, use the followingcommands.

Command Description

TTITLE Displays the current setting for the header.

TTITLE OFF Turns the header off.

BTITLE Displays the current setting for the footer.

BTITLE OFF Turns the footer off.

Page 248: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������/,

Page 249: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��/-

���� ��� � ����� ������

���� ��� %� ����� 4��� � ��� � �����

You can either enter each of the SQL*Plus commands at the SQL prompt or put allthe commands, including the SELECT statement, in a command (or script) file. Atypical script consists of at least one SELECT statement and several SQL*Pluscommands.

� ��� � ���� � � ����� 4���

1. Create the SQL SELECT statement at the SQL prompt. Ensure that the datarequired for the report is accurate before you save the statement to a file andapply formatting commands. Ensure that the relevant ORDER BY clause isincluded if you intend to use breaks.

2. Save the SELECT statement to a script file.

3. Edit the script file to enter the SQL*Plus commands.

4. Add the required formatting commands before the SELECT statement. Be certainnot to place SQL*Plus commands within the SELECT statement.

5. Verify that the SELECT statement is followed by a run character, either asemicolon (;) or a slash (/).

6. Add the format-clearing SQL*Plus commands after the run character. As analternative, you can call a reset file which contains all the format-clearingcommands.

7. Save the script file with your changes.

8. In SQL*Plus, run the script file by entering START filename or @filename. Thiscommand is required to read and execute the script file.

5���������

� You can include blank lines between SQL*Plus commands in a script.

� You can abbreviate SQL*Plus commands.

� Include reset commands at the end of the file in order to restore the originalSQL*Plus environment.

Page 250: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������0

/

������/ ���� ����� ���

�����

� �������

Page 251: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���/

���� ��� � ����� ������

&2�'���

Create a script file to create a report which displays the job title, last name, and salaryfor every employee who is not a vice president or a warehouse manager. Add acentered, two-lined header that reads Employee Report, and a centered footer thatreads Confidential. Rename the title column to read Job Category split over two lines.Rename the employee name column to read Employee. Print the salary column withthe label in initial capitalization and formatted as $2,500.00.

REM ** This report covers all employees who are notREM ** vice presidents or warehouse managers.SET ECHO OFFSET PAGESIZE 37SET LINESIZE 60SET FEEDBACK OFFTTITLE ’Employee|Report’BTITLE ’Confidential’COLUMN title HEADING ’Job|Category’ FORMAT A22COLUMN last_name HEADING ’Employee’ FORMAT A22COLUMN salary HEADING ’Salary’ FORMAT $99,999.99

REM ** Insert SELECT statementSELECT title, last_name, salaryFROM s_empWHERE title NOT LIKE ’VP%’ AND title <> ’Warehouse Manager’ORDER BY title, last_name, salary/REM ** Run a reset command fileSTART reset.sqlSET ECHO ON

REM represents a remark or comment in SQL*Plus.

Page 252: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� �����������

3�������� ��� ���� ��� ����� ����6�

Page 253: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ����

3�������� ��� ���� ��� ����� ����6�

You can use two methods to process PL/SQL blocks in SQL*Plus.

� Define a block in the SQL buffer, then execute the contents of the buffer.

� Define a block as part of a SQL*Plus script file, then start the file.

3�������� ����� ����6� �� %� ��� ��..��

A PL/SQL block is treated as one continuous statement in the buffer, and thesemicolons (;) within the block do not close or execute the contents of the buffer.

SQL*Plus detects the start of a PL/SQL block when you enter either DECLARE orBEGIN at the prompt. You can close the buffer without executing the block byentering a period (.) at the number prompt of the buffer.

To run the buffered PL/SQL block, enter the RUN command or a slash (“/”) at theprompt. If the block executes successfully, without unhandled exceptions or compileerrors, you will see a message.

���� ��� ������ 4���� ��� ������ ����� ����6�

You can include PL/SQL blocks in files of SQL and SQL*Plus commands. Create thefile using the operating system editor. SQL*Plus commands may not occur inside thePL/SQL block itself, but you can include them elsewhere in the file.

You can reference SQL*Plus substitution variables inside the block, but rememberthat they are substituted with the variable’s contents before the code is parsed orexecuted. This means that if you reference a SQL*Plus substitution variable in aPL/SQL loop, then a value is substituted for the variable once, and not for eachiteration of the loop.

Page 254: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������#

������ ��''����

Page 255: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���(

&� ����� ��''���� �� ������

SQL*Plus contains an array of commands to format reports and initiate the users’environment.

SQL*Plus Command Description

ACCEPT Reads input from the user and stores the input into avariable.

VARIABLE Declares a bind, or host, variable that can bereferenced in PL/SQL with a preceding colon (:).

PRINT Displays the current value of bind variables.

EXECUTE Executes a single PL/SQL statement.

For more information, seeSQL*Plus User’s Guide and Reference, Release 3.3.

Page 256: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������*

Page 257: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���+

������ ���� ��� �� �� 7�����

A substitution variable, or parameter, preceded by an ampersand (&) is used torepresent a value to be passed into a statement. A global variable preceded by a colon(:)is used to pass information out of the PL/SQL block.

���� 7�����

From SQL*Plus, input a value into the PL/SQL block by means of a SQL*Plussubstitution value. Follow the steps listed below.

1. Outside the PL/SQL block, assign a value from the keyboard into a SQL*Plussubstitution value with the SQL*Plus ACCEPT command.

2. Within the PL/SQL block, embed the SQL*Plus substitution parameter whereverit is needed as input, referencing it with the ampersand (&) prefix.

�1� �2

ACCEPT variable PROMPT message

where: variable is the name of the substitution variable to storethe value.

message is the message displayed.

Page 258: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������,

Page 259: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���-

������ ���� ��� �� �� 7����� ������

�� �� 7�����

Output a value from the PL/SQL block into SQL*Plus by using a SQL*Plus globalvariable. Follow the steps listed below.

1. Outside the PL/SQL block, declare a SQL*Plus global variable with theSQL*Plus VARIABLE command.

2. Within the PL/SQL block, embed the SQL*Plus global variable wherever it isneeded as output, referencing it with the colon (:) prefix.

3. Outside the PL/SQL block, print the output value on the screen with theSQL*Plus PRINT command.

�1� �2

VARIABLE variable [NUMBER|CHAR|CHAR(n)|VARCHAR2(n)]

PRINT variable

where: variable is the name of the bind variable.

n is the maximum length for the datatype.

Page 260: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������0

Page 261: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���/

3� ������ �� ������

When you execute your PL/SQL code, one of two types of errors might appear. Onetype is a compilation error. For anonymous blocks, you will see the errors appear onthe screen. For stored subprograms, the compilation errors are stored in theUSER_ERRORS data dictionary table. To access those errors, enter either of thefollowing commands at the prompt:

SQL> SHOW ERRORS

SQL> SELECT *2 FROM user_errors;

The second type of error you can encounter is an exception, which is a message fromthe PL/SQL engine indicating that an error occurred while performing some of thetasks in the block. Handling of exceptions is covered in lesson 25 of this course.

Page 262: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� �����������

Page 263: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ����

3� ������ �� ������ ������

One method for debugging your PL/SQL block using SQL*Plus is to embed globalvariables at specific points with a message. Each message can contain informationabout how many times a loop was executed, or which statements were executed. Youcan print the results of the global variables using the SQL*Plus PRINT command.

&2�'���

Print a message indicating which DML statement was executed.

VARIABLE g_debug VARCHAR2(50)ACCEPT p_num PROMPT ’Enter a number: ’DECLARE v_num NUMBER := &p_num;BEGIN IF MOD(v_num,2) = 0 THEN UPDATE... :g_debug := ’Even number entered.’; ELSE INSERT... :g_debug := ’Odd number entered.’; END IF;END;/

SQL> START test

Enter a number: 10

PL/SQL procedure successfully completed.

SQL> PRINT g_debug

G_DEBUG----------------------------------------------------Even number entered.

Page 264: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������#

Page 265: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���(

3�����1��� ��� �� � �. � �� ������'

You can obtain the text of a stored procedure or a function from USER_SOURCEdata dictionary view.

&2�'���

Display contents of the procedure CHANGE_SALARY.

SQL> SELECT text2 FROM user_source3 WHERE type = ‘PROCEDURE’4 and name = ‘CHANGE_SALARY’;

TEXT––––––––––––––––––––––––––––––––––––––––––––––––––––PROCEDURE change_salary

(v_emp_id IN NUMBER,v_new_salary IN NUMBER)

ISBEGIN

UPDATE s_empSET salary = v_new_salaryWHERE id = v_emp_id;COMMIT;

END change_salary;

Page 266: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������*

Page 267: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���+

&2��� ��� � ���� �� ������'�

Once you create your stored programs, you invoke them by using the SQL*PlusEXECUTE command.

&2��� ��� � ���� ���������

The EXECUTE command runs the PL/SQL statement stored in the database.

�1� �2

EXECUTE procedure_name [(argument_list)]

where: procedure_name is the name of the procedure.

argument_list is the set of variables, expressions, constants, orliterals passed to the procedure.

&2��� ��� � ���� 4��� ����

Functions require that a value be returned. Therefore, you call the function as part ofan expression. Create a global variable to hold the returned value when using theEXECUTE command.

�1� �2

EXECUTE variable := function_name [(argument_list)]

where: procedure_name is the name of the function.

argument_list is the set of variables, expressions, constants, orliterals passed to the function.

Page 268: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ����������,

Page 269: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ���-

&2��� ��� � ���� �� ������'� ������

Issue SQL commands and evaluate PL/SQL constructs.

&2�'���

Enter a data definition language (DDL) statement at the command prompt to createthe B_TEST table.

SQL> CREATE TABLE b_test (col1 NUMBER);

Insert three rows in the B_TEST table using a PL/SQL statement.

SQL> CREATE PROCEDURE testproc IS2 BEGIN3 FOR i IN 1..3 LOOP4 INSERT INTO b_test VALUES (i);5 END LOOP;6 END;7 /

Procedure created.

Execute the procedure.

SQL> EXECUTE testproc;

PL/SQL procedure successfully completed.

Display the contents of the B_TEST table.

SQL> SELECT * 2 FROM b_test;

COL1--------- 1 2 3

Page 270: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������#0

Page 271: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��#/

��''��1

�������� ��� ����� ����� ������

You can use SQL*Plus to create, debug, and execute PL/SQL blocks

� Create and modify anonymous blocks and program units with SQL*Plus and theonline editor.

� Execute SQL*Plus commands, anonymous blocks, program units, and SQLstatements.

� Compile procedures and functions.

� Create and manipulate SQL*Plus variables for passing values in and out of yourPL/SQL block.

� Embed messages to assist with debugging code.

��� ��� ������ ��'��������

SQL and SQL*Plus are distinctively different languages, but are used together tocreate reports. SQL communicates with the Oracle7 Server to access data. The SQLcommands are stored in the SQL buffer, and they are executed by a terminationcharacter. SQL*Plus commands recognize SQL commands and send them to theOracle7 Server. SQL*Plus commands are entered one line at a time and are not storedin the SQL buffer.

������ ��''����

SQL*Plus commands are useful in developing reports that are based on a query. Theycan set up the environment at log in when they reside in the login.sql file.

Page 272: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������#�

Page 273: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��#�

��� ��� �"��"��)

This practice will familiarize you with the SQL*Plus commands used to build reportsand those used with PL/SQL blocks.

��� ��� ��� �� �

� Distinguishing between SQL and SQL*Plus

� Customizing reports

� Executing a PL/SQL anonymous block

� Creating and executing a stored function

Page 274: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������##

Page 275: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��#(

��� ��� �

1. Determine whether each of the following commands is a SQL or SQL*Pluscommand. Place a check in the appropriate column.

Command SQL SQL*Plus

DESCRIBE

SPOOL

SELECT

SET

RUN

INSERT

2. The number of tasks on the left do not match the commands listed on the right.Draw lines to match the correct command to the correct task.

Task Command

Display the definition of a table. SET LINESIZE

Suppress the message displaying thenumber of rows returned from a query.

SPOOL

Control the character length of a line. DESCRIBE

Specify a heading to appear at the topof each report page.

SET FEEDBACKOFF

Alter the display characteristics of acolumn.

TTITLE

Document a command or script file. COLUMN

Send output to a file for printing later. REM

Page 276: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������#*

��� ��� � ������

3. Load and execute a loop counter.

a. Launch SQL*Plus. Your instructor will give you the login information.

b. Start the LABS\pcloop.sql file to create the COUNT_LOOPS procedure.

c. View the arguments for the COUNT_LOOPS procedure by using theDESCRIBE command.

d. Create a global variable named G_OUTPUT to hold a text string from theargument V_OUTPUT.

e. Execute the COUNT_LOOPS procedure.

f. Display the value in the G_OUTPUT global variable.

4. Execute an anonymous PL/SQL block that accepts a number and determines if itis odd or even.

a. Start the LABS\pcmsg.sql file to execute the PL/SQL block.

b. Enter a value at the prompt. Sample values are 3, “hello”, “NULL”, and 6

c. Display the value in the G_MESSAGE global variable.

Page 277: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��#+

��� ��� � ���� ����

1. Determine whether each of the following commands is a SQL or SQL*Pluscommand.

Command SQL SQL*Plus

DESCRIBE X

SPOOL X

SELECT X

SET X

RUN X

INSERT X

2. The number of tasks on the left do not match the commands listed on the right.Draw lines to match the correct command to the correct task.

Task Command

Display the definition of a table. SET LINESIZE

Suppress the message displaying thenumber of rows returned from a query.

SPOOL

Control the character length of a line. DESCRIBE

Specify a heading to appear at the top ofeach report page.

SET FEEDBACKOFF

Alter the display characteristics of acolumn.

TTITLE

Document a command or script file. COLUMN

Send output to a file for printing later. REM

Page 278: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������#,

��� ��� � ���� ���� ������

3. Load and execute a loop counter.

a. Launch SQL*Plus. Your instructor will give you the login information.

b. Start the LABS\pcloop.sql file to create the COUNT_LOOPS procedure.

SQL> START c:\labs\pcloop

Procedure created.

c. View the arguments for the COUNT_LOOPS procedure by using theDESCRIBE command.

SQL> DESCRIBE count_loops

PROCEDURE count_loops Argument Name Type In/Out Default? --------------------- ------------- ----- -------- V_COUNT NUMBER IN V_OUTPUT VARCHAR2 OUT

d. Create a global variable named G_OUTPUT to hold a text string from theargument V_OUTPUT.

SQL> VARIABLE g_output VARCHAR2(50)

e. Execute the COUNT_LOOPS procedure.

SQL> EXECUTE count_loops (4, :g_output);

PL/SQL procedure successfully completed.

f. Display the value in the G_OUTPUT global variable.

SQL> PRINT g_output

G_OUTPUT-------------------------------------------4 times through the loop

Page 279: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����� ������ � ���� � ����� � ��� ������ ����� ���� ��#-

��� ��� � ���� ���� ������

4. Execute an anonymous PL/SQL block that accepts a number and determines if itis odd or even.

a. Start the LABS\pcmsg.sql file to execute the PL/SQL block.

b. Enter a value at the prompt. Sample values are 3, “hello”, “NULL”, and 6

c. Display the value in the G_MESSAGE global variable.

SQL> START c:\labs\pcmsg

Enter a number: 3

PL/SQL procedure successfully completed.

SQL> PRINT g_message

G_message-------------------------------------------ODD number

SQL> START c:\labs\pcmsg

Enter a number: hello”hello” is not a valid numberEnter a number: NULL”null” is not a valid numberEnter a number: 6

PL/SQL procedure successfully completed.

SQL> PRINT g_message

G_message-------------------------------------------EVEN number

Page 280: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�� ����� ��� � ������� ��� ��� ����� ����� �������� ���������(0

Page 281: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

������� ������ � � ��������

Page 282: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

� ������ � ������� ��� � � ������ ��� � ������� ���������

Page 283: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

������� ������ � � �������� ���

������� ������

DBA*Assist Version 1.4 is a SQL*Forms application that aids the DBA in managingthe Oracle Version 6.0 database. Using a simple and effective menu structure,DBA*Assist provides a powerful productivity tool to simplify Oracle databaseadministration in the key areas below.

���� ��� �� � ��

� Query, add, and alter database users and their attributes.

����� ��!���

� Displays information screens on tablespace size, usage and fragmentation at thethree distinct levels of tablespace, user and object.

����� "���#���

� Define tables and indexes and perform “what if” analysis to estimate space andproper storage procedures.

$�%������� � � ���%��& ���#� � ��� �� � ��

� Query, add, drop, and alter tablespaces and rollback segments.

'��� ��������

� Invoke DBA*Assist as a client SQL*Forms application and “manage” the targetdatabase over a SQL*Net connection.

Page 284: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

� ������ � ������� ��� � � ������ ��� � ������� ��������(

Page 285: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

������� ������ � � �������� ��)

������� ��������

When you need to augment your internal resources, need specific technical expertise,or are seeking to maximize your technology investments fully, partnering with OracleServices is the answer. No one is more qualified than the Oracle Services team ofconsultants to help you implement, customize, or integrate client-server technology.

Our 3,500 consultants in 43 countries can help you with local projects orenterprise-wide, global, or multi-size implementations. We work closely with yourin-house staff to ensure that the solutions are tailored to your needs, and to transferthe skills required to maintain and expand the completed system.

������ ' ���� �

� Business Process Reengineering (BPR) increases productivity by rapidlyproviding you with efficient, streamlined yet flexible processes and technologysolutions that support your strategy.

� Custom Application Development draws upon our tools and CASE experienceto deploy rapidly specialized, easy–to–maintain client-server applications for yourbusiness.

� Applications Consulting services offer experienced consultants who specializein rapidly implementing Oracle Cooperative Applications.

� Oracle Industries develops integrated solutions for specific industries using acombination of Oracle and third-party products and services.

� Core Technology Services help you through support, system and applicationsaudits, performance tuning, and technology upgrades.

� Open Systems Transformation services provide an architecture andimplementation road map to transfer systems from legacy environments toclient-server.

For more information on Oracle Services, please call 1–800–ORACLE1 or contactyour local Oracle office.

Page 286: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

� ������ � ������� ��� � � ������ ��� � ������� ��������*

Page 287: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������

��������

A

actual parameter The variable orexpression referenced in the parameterlist of a subprogram call.

Ada A high-level programminglanguage developed by the U.S.Department of Defense for use inembedded computer systems.

alias A temporary name assigned to atable, view, column, or value within aSQL statement, used to refer to that itemlater in the same statement or inassociated SQL*Plus commands.

anonymous block A PL/SQL programunit that has no name and does not requirethe explicit presence of the BEGIN andEND keywords to enclose the executablestatements. Since they are unnamed,anonymous blocks cannot be referencedby other program units.

application One or more programmodules used to achieve a specific result.Applications can be nested within otherapplications. For example, an applicationto control a company’s inventory couldconsist of various Forms applications forinput of data, and various Graphicsapplications to display the data visually.

application subprogram A procedureor function that resides and executes in anapplication.

argument 1. An expression within theparentheses of a subprogram, supplying avalue for the subprogram to operate on.For example, in the expression

MY_PROC(x), x is the argument. 2.Clauses containing keywords and theirspecified values. For example,‘PRINT=YES’ is an argument.

ASCII Acronym for American NationalStandard Code for InformationInterchange.

Bbatch compile To translate, at once,several PL/SQL program units into amachine executable form.

bind reference A reference to aparameter used to replace a single literalvalue (for example, a character string,number, or date) appearing anywhere in aPL/SQL construct or a SQL SELECTstatement. For a bind reference, you mustprecede the parameter name with a colon(:). See also: lexical reference, parameter,global variable.

bind variable A global variable you cancreate outside of a package in astandalone session of Procedure Builder.

block The basic program unit inPL/SQL, defined by the keywordsDECLARE, BEGIN, EXCEPTION, andEND.

body Contains the same information asthe program unit specification, and alsoincludes the actual implementation of thesubprogram (that is, its sequence ofactions). In most cases, only a body mustbe defined for a subprogram.

breakpoint A debug action you canplace at any source in a PL/SQL

Page 288: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������

subprogram that interrupts execution ofthe program unit and passes control to thePL/SQL Interpreter. Breakpoints allowyou to incrementally execute asubprogram.

built-ins A collection of extensions tothe PL/SQL language that are designed tobe used with Developer/2000. Built-insinclude datatypes, procedures, functions,exceptions, and constants.

buffer A temporary storage area for dataduring the transfer of that data betweenthe computer and a peripheral, or betweenparts of a computer. A buffer preventsloss of information due to differences inthe speed or timing of the transfer andspeeds up certain functions.

C

call stack A chain of subprogram calls,from the initial entry point down to thecurrently executing subprogram. Eachsubprogram call is represented by a frameon the downward-growing call stack, inwhich newly entered subprograms areadded to the bottom of the stack.

Cartesian product When youdeactivate a relationship that is the onlypath relating two data sources, thenexecute a query using fields from bothsides of the relationship, the result is aCartesian product. The query combinesall rows from all included data sources.A Cartesian product always retrievesmany rows and information that isseldom useful. For example, if two datasources each contain 100 rows, the

resulting Cartesian product will be10,000 rows.

CHAR datatype An Oracle datatypeprovided for ANSI/ISO compatibility. ACHAR column is a fixed-length columnand can contain any printable characters,such as A, 3, &, or blanks, and can havefrom 1 to 255 characters or can be null.

child An object that is a member of agroup, and is immediately below thatgroup object in its group tree. The objectsthat compose a group object are childrenof that group. Every object is a child of itsparent.

clause A part of a SQL statement thatdoes not constitute the full statement; forexample, a “WHERE clause.”

client A user, software application, orcomputer that requests the services, data,or processing of another application orcomputer (the “server”). In a two-taskenvironment, the client is the userprocess. In a network environment, theclient is the local user process and theserver may be local or remote.

client-server architecture Separation ofprocessing between two CPUs, oneacting as the server that provides servicesin a transaction and the other as the clientin the transaction, requesting andreceiving services. All responsibilities ofshared data management can beprocessed by the computer running thedatabase management system while theworkstations running the databaseapplication concentrate on theinterpretation and display of data.

Clipboard A memory buffer. Anobject remains on the Clipboard until you

Page 289: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����������

cut or copy another object, or until youquit the application.

column A vertical space in a databasetable that represents a particular domainof data. A column has a column name (forexample, ENAME) and a specificdatatype (for example, CHAR). Forexample, in a table of employeeinformation, all of the employees’ nameswould constitute one column. A recordgroup column represents a databasecolumn.

command line An operating-systemcommand line. Most Oracle products canbe invoked from a command line using anumber of executable arguments.

commit To make changes to data(inserts, updates, deletes) in the databasepermanent. Before changes are stored,both the old and new data exist so thatchanges can be stored or the data can berestored to its prior state.

compile To translate a source programas into a binary, executable format.PL/SQL program units must be compiledbefore they can be executed.

composite datatype Datatype composedof multiple components.

condition An expression whose valueis either true or false, such as X> 100. Forexample, you can set a condition in aquery when you want the query to displayonly those rows that evaluate as true inyour expression.

connect To log on to a database. Youmust connect if you want to create or

modify queries or access an applicationstored in a database.

connect string The set of parameters,including a protocol, that SQL*Net usesto connect to a specific Oracle instance onthe network.

constraint A rule or restrictionconcerning a piece of data (such as a NOTNULL restriction on a column) that isenforced at the database level, rather thanthe object or application level.

construct A PL/SQL code structure.There are two types of constructs:non-value constructs do not return avalue; value constructs return a value.

control structures Programmingstructures related to decision-making:selection, iteration, and sequence.

copy To store a replica of a selectedobject on the Clipboard, so that it may bepasted elsewhere in an editor if desired.

Cue Cards Just-in-time coaching forfrequently performed tasks. Available inOracle Procedure Builder.

cursor 1. A small icon representing theposition of the mouse. The shape of thecursor varies, depending on the selectedtool. 2. An internal pointer to dataretrieved by a query. A cursor points onlyto one row of data at a time; however, youcan use built-in subprograms to move thecursor to any row in the data set.

cut To delete one or more objects andstore them in the Clipboard, so that theymay be pasted elsewhere in an editor, ifdesired.

Page 290: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����������

D

data control language (DCL) Thecategory of SQL statements that controlaccess to the data and to the database.Examples are the GRANT and REVOKEstatements. Occasionally DCLstatements are grouped with DMLstatements.

data definition language (DDL) Thecategory of SQL statements that define ordelete database objects such as tables orviews. Examples are the CREATE,ALTER, and DROP statements.

data dictionary A set of tables andviews owned by the databaseadministrator. It is a central source ofinformation for Oracle Server and otherrelational databases.

data manipulation language (DML)The category of SQL statements thatquery and update the database data.Common DML statements are SELECT,INSERT, UPDATE, and DELETE.Occasionally DCL statements aregrouped with DML statements.

data model A relational model thatdefines what data should be fetched fromthe database, what values should becomputed, and how data should beordered in a report. Reports objects thatdefine the data model are queries, groups,columns, parameters, and links.

database A set of dictionary tables anduser tables that are treated as a unit.

datatype A standard form of data. TheOracle datatypes are CHAR, DATE,

NUMBER, LONG, RAW, and LONGRAW.

DATE An Oracle Server datatype. Adate column may contain a date and timebetween January 1, 4712 B.C. andDecember 31, 4712 A.D.

debug To detect, diagnose, andeliminate errors in programs.

debug action An user specified eventplaced in a PL/SQL subprogram usingProcedure Builder functionality, usuallyfor the purpose of troubleshooting errorsraised during subprogram execution. Seealso: breakpoint, debug trigger.

debug trigger A conditional debugaction you can place at any source line ina PL/SQL subprogram. If the specifiedcondition is met, the specified action istaken before execution of the subprogramresumes.

debugger The Procedure Builderfunctionality within anotherDeveloper/2000 component thatsimulates runtime execution of anapplication for testing and debugging.

default A value supplied by the systemwhen a user does not specify a requiredcommand parameter or attribute.

descendant An object that appears inanother object’s group tree at any positionbelow that other object. Every object is adescendant of its antecedents.

drag Press and hold down a mousebutton while you slide the mouse pointerto a particular location in a window.

duplicate An option that allows you tocopy objects directly on the layout

Page 291: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������

without affecting the contents of theClipboard. See also: copy.

E

editor A work area in which youperform a specific set of tasks, such ascreating a program unit or designing anapplication.

equijoin A type of join where the joincondition is an equality, such as WHERES_EMP.DEPT_ID = S_DEPT.ID.

exception A warming or error conditiongenerated from a PL/SQL subprogram.

executable argument An argument youcan pass to a product executable, such as‘OPENFILE=my_disp’ and‘PRINT=YES’. These arguments usuallyare specified when the executable isinvoked from a command line.

export To store a copy of a module toa file or database.

expression A PL/SQL constructcombining variables, constants, literals,and operations on their values.

external PL/SQL library See library.

external query An ANSI-standard SQLSELECT statement that can bereferenced by other Oracle products.

F

field The data stored at the intersectionof a row and a column.

foreign key A value or column in onetable that refers to a primary key inanother table.

formal parameter The variabledeclared in a subprogram specificationand referenced in the subprogram body.

function A PL/SQL subprogram thatexecutes an operation and returns a valueat the completion of the operation. Afunction can be either built-in oruser-named. Contrast with procedure.

Gglobal variable A logical container thatexists across an application. When anapplication uses a global variable, theapplication maintains the variable untilthe application is exited, or until anotherobject explicitly removes it. See also:parameter, bind variable, local variable

grant To give a user access to a module.Only a module’s creator can grant itsaccess to other users.

group function A SQL function thatcomputes a single summary value fromthe individual values in specified groupsof rows. Examples are AVG, MAX, orSUM.

GUI Acronym for Graphical UserInterface. Also known as a bitmappedinterface.

Hheading node A node in the ObjectNavigator denoting a type of objectwhich can be contained within or

Page 292: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����������

associated with a report. Selecting aheading node does not select an object inthe report.

host variable See global variable.

I

icon A graphic representation of awindow or tool.

identifier See name.

IF statement Control structure thatallows you to execute a sequence ofstatements conditionally.

import To read a module from the filesystem or database, and incorporate itinto an application.

index An optional structure associatedwith a table that is used by Oracle Serverto locate rows of the table quickly, and(optionally) to guarantee that every row isunique.

insert mode A mode in which eachcharacter you enter is inserted at thecursor, pushing the following charactersto the right. The opposite of Replacemode.

Interpreter Define, display, debug, andexecute Pl/SQL program units in theInterpreter window of Oracle ProcedureBuilder.

Interpreter script A file containing anymixture of PL/SQL source, ProcedureBuilder commands, and SQL statements.

Jjoin Combining data from two (or more)tables in a single SELECT statement.

Kkeyword Part of a command line syntaxthat must be supplied with acorresponding argument.

Llexical reference A reference to aparameter used to represent a string oftext in a SQL SELECT statement. For alexical reference, you must precede theparameter name with an ampersand (&).See also: bind reference, parameter

library A collection of one or morePL/SQL program units that are storedtogether in a file or database, and that canbe referenced by several applications atonce.

local database 1. The database on thecomputer running the application. 2. Thedatabase to which an application isconnected. This database parses andexecutes all SQL statements generated bythe application. See also: NO TAGremotedatabase.

local variable A PL/SQL variabledeclared only within the scope of thecurrent program unit. See also:parameter, bind variable, globalvariable.

LONG datatype A standard ORACLEdatatype. A LONG column may containany printable character, such as A, 3, &,

Page 293: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����������

or blanks, and can be any length from 1 to65K characters; alternatively it can benull.

loop In a PL/SQL subprogram, aconditional statement that is repeateduntil the condition is no longer met.

M

megabyte (Mb) A unit of memory equalto 1,048,576 bytes (1024 x 1024). Oftenrounded to one million bytes.

module An object that can be shared bymultiple applications. External queriesand PL/SQL libraries are examples ofmodules.

N

name The unique identifier given to anobject.

node A specific location in the ObjectNavigator object hierarchy. Nodes can beexpanded to reveal information about anobject, such as cross references to otherobjects.

NULL value The absence of a value.

Number datatype A standard ORACLEdatatype. A NUMBER column cancontain a number, with or without adecimal point and a sign, and can havefrom 1 to 105 decimal digits (only 38digits are significant).

OObject Navigator The windowcontaining a hierarchical list of objectsfor the current session. The list appears inoutline form, and enables the user toaccomplish several tasks such as creating,editing, renaming, and deleting objects.

object privileges Privileges granted(assigned) to end users so that they canuse a database application to accomplishspecific tasks. Object privileges performa particular action on a specific object.For example, the privilege to delete rowsof a specific table is an object privilege.

outer join A type of join that returnsrows from one table that do not satisfy thejoin condition, in addition to those that dosatisfy the condition. Each additional rowis joined to an imaginary row in the othertable in which all the fields are null.

Ppackaged function A PL/SQL functionprovided with Developer/2000 that canbe referenced anywhere within a programunit.

package A method of encapsulating andstoring related procedures, functions,variables, and other package constructstogether as a unit in the database. Whilepackages provide the databaseadministrator or application developerorganizational benefits, they also offerincreased functionality and databaseperformance.

package body Includes the actualimplementation of the package, whichmay include private subprograms and

Page 294: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����������

datatypes. The body is optional if thepackage consists only of declarations.

package specification Declares thepublic interface to the package—that is,the datatypes and subprograms that canbe referenced by other program units.

pane A distinct portion of an editorwhere work is performed, usuallyresizeable.

parameter A global variable that isdefined in an application and existsoutside of a PL/SQL package orsubprogram. See also: bind reference,lexical reference.

parameter list A named programmaticconstruct that lists parameter names(called keys), their types, and theirvalues.

parent An object that is immediatelyabove another object in its group tree. Agroup object is the parent to each of theobjects that compose it. Every object isthe parent of its children.

paste To place the contents of theClipboard (cut or copied objects) on thelayout.

PL/SQL A procedural extension of SQLthat provides programming constructssuch as conditionals and procedures.

.pld The standard extension given to thefile representation of a Procedure BuilderInterpreter script.

.pll The standard extension given to thefile representation of a PL/SQL library.

.pls The standard extension given to aPL/SQL program unit that has beenexported to a text file.

primary key In a database table, a set ofcolumns used to enforce uniqueness ofrows. The combination of column valuesis unique for each row in the table. Theprimary key is the most frequently usedmeans of accessing rows.

privilege A right to successfully executea particular type of SQL statement. Someexamples of privileges include rights toconnect to the database (create a session),to create a table in your schema, to selectrows from someone else’s table, and toexecute someone else’s stored procedure.The privileges of an Oracle database canbe divided into two distinct categories:system privileges and object privileges.

procedure A PL/SQL subprogram thatperforms a specified sequence of actions.

program unit A code structure you cancreate using PL/SQL. Anonymousblocks, subprogram specifications andbodies, and package specifications andbodies are examples of program units.See also: subprogram

protocol A string you can enter whenconnecting to a database or server thatallows you to connect to a remotedatabase or server.

pull-down menu A set of options,displayed horizontally under theapplication window title. Each option canrepresent a submenu or an action.

Qquery A SQL SELECT statement thatspecifies the data you wish to retrieve

Page 295: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����������

from one or more tables or views of adatabase.

Quick Tour Online help used tointroduce you to product terminology,workflow, and theoretical concepts.Available in Oracle Procedure Builder.

quit An option that terminates thecurrent session and returns the user to theoperating system. On some systems, Quitis Exit.

R

RDBMS (Relational DatabaseManagement System) An OracleVersion 6 (and earlier) term. Refers to thesoftware used to create and maintain thesystem, as well as the actual data stored inthe database.

record One row fetched by a SELECTstatement.

relational operator A symbol used insearch criteria to indicate a comparisonbetween two values, such as the equalsign in “WHERE DEPTNO = 10.” Rowsin which the comparison results in“TRUE” are returned in the result(fetched), while rows in which thecomparison returns “FALSE” arerejected from the result.

replace mode A mode in which eachcharacter you enter replaces the currentcharacter at the cursor. The opposite ofinsert mode.

roles Named groups of relatedprivileges that are granted to users orother roles.

row One set of field values in a table;for example, the fields representing oneemployee in the example table S_EMP.

Sschema A collection of related objects.Schema objects includes tables, views,sequences, stored program units,synonyms, indexes, clusters, anddatabase links.

scope The level at, or range in which,an object operates.

script See SQL script, Interpreter script

SELECT statement A SQL statementthat specifies which rows and columns tofetch from one or more tables or views.See also: SQL statement, query

sequence A database structure used togenerate unique integers to be used asprimary keys (which are guaranteed to beunique). Concurrent database users canuse a sequence simultaneously.Sequences may be defined with manycharacteristics (for example, to ascend ordescend, have any increment ordecrement, and to recycle values or not).

session The period between invokingand quitting the executable.

source PL/SQL statements provided ina subprogram or package. You must havethe source code for a program unit beforeyou can compile it into executable form.

specification Defines only the names,parameters, and return type (applies tofunctions only) of the subprogram.

split bar A small rectangle at the bottomof the vertical scroll bar and to the left of

Page 296: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

����������

the horizontal scroll bar in an editor.Dragging and releasing the mouse buttoncreates a pane, creates a new split bar atthat location, and divides the scroll barinto separate scroll bars for each pane. Seealso: pane, scroll bar.

SQL Standard interface for storing andretrieving information in a relationaldatabase. SQL is an acronym forStructured Query Language.

SQL buffer In SQL*Plus, the defaultbuffer used to contain the SQL commandor PL/SQL block most recently entered.

SQL*Plus An interactive SQL-basedlanguage for data manipulation, datadefinition and the definition of accessrights for an Oracle database. Often usedas an end-user reporting tool.

SQL script A file containing SQLstatements that you can run to performdatabase administration quickly andeasily. Several SQL scripts are shippedwith Oracle products.

SQL statement A SQL instruction toOracle. A SELECT statement is one typeof SQL statement. See also: SELECTstatement, query

stack See call stack.

statement A PL/SQL construct used forconditional, iterative, and sequentialcontrol, and for error handling. Asemi-colon (;) must terminate everyPL/SQL statement.

stored program unit A procedure,function, or package that resides andexecutes in the Oracle7 Server.

stored subprogram A procedure orfunction that resides and executes in theOracle7 Server. Procedure Builder cancall stored subprograms.

subprogram A PL/SQL procedure orfunction. See also: program unit

subquery A query that is nested in aclause of a SQL command.

substitution parameter Atwo-character variable of type CHARthat is referenced in a menu itemcommand or in a PL/SQL program unit,and substituted with a value at runtime.

synonym An alias for a table, view,sequence, or program unit; a synonym isnot actually an object itself, it is a directreference to its base object. Synonyms areused to mask the real name and owner ofan object, provide public access to anobject, provide location transparency fortables, views, or program units of aremote database, and simplify the SQLstatements for database users. A synonymcan be public or private.

syntax The orderly system by whichcommands, qualifiers, and parameters arecombined to form valid commandstrings.

Ttable A named collection of relatedinformation, stored in a relationaldatabase or server, in a two-dimensionalgrid that is made up of rows and columns.

toggle A setting that can be turned eitheron or off. For example, you can hide orshow the Object Navigator.

Page 297: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������

tool An icon that appears in the Layouteditor or Object Navigator. Tools are usedto create and manipulate objects in anapplication.

toolbar Collection of iconic buttons thatperform product commands. Usuallyaligned horizontally along the top, orvertically down the side of a window.

transaction A sequence of SQLstatements treated as a single unit.

trigger A PL/SQL procedure that isexecuted, or “fired,” at upon a specificevent.

Uupdate To change the values for tabledata, in particular, by altering data valuesusing the SQL command UPDATE, butalso by deleting values using the SQLcommand DELETE or by insertingvalues using the command INSERT.

user-named parameter A type ofsubstitution parameter that is created inthe Forms designer (valid for a givenmenu module).

VVARCHAR2 datatype Equivalent to theCHAR datatype, a standard Oracledatatype used to store character

(alphanumeric) data. In Oracle RDBMSV6, CHAR and VARCHAR areequivalent. In Oracle7, CHAR data isfixed-length and VARCHAR isvariable-length.

variable A named object that can beassigned a value and whose assignedvalue may change over time. See also:parameter, bind variable, globalvariable, local variable

view A virtual table whose rows do notactually exist in the database, but which isbased on a table that is physically storedin the database.

W

wildcard A character used to mean “anyone character” or “a contiguous set ofcharacters” within a word or phase.

window A rectangular area of thedesktop that contains an application.Each window has an area where you caninteract with the application. Windowscan be opened, resized, moved, reducedto an icon, or enlarged to fill the entiredesktop.

XYZ

zoom To expand an object to allow moreroom for editing the contents of the field.

Page 298: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���������

Page 299: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�����

�����

�� ��� ������

�� ��� ��

� � ��� ���������� ������

��� ��� ������� �����

��� ��� ������� �����

���� ��� ���� ��� ������

�� ��� ���������

� ��� ������ ������!���

"� ��� ���#

$� ��� ��������

%%� ��� ����������� ������

&''()* ������+ ,-./+ ..-.,

����0� ���+ 12-..+ 12-.3+ 12-./

��������+ .-1.+ 1-,+ .2-..��4�+ 2-.3

&5*(6 �(78(9'( ������+ .3-.,

&5*(6 *&:5( ������+ .1-,&;; �����+ .1-,��� �����+ .1-,&;; ��������� �����+ .1-..;(<&85* ��=>��+ .1-,;?�&:5( �����+ .1-./;6@) ��������� �����+ .1-..(9&:5( �����+ .1-./A@;?<B �����+ .1-C���!= �����+ .1-C9@* 9855 ���������+ .1-,

&5*(6 8�(6 ������+ ����>��+ .D-.3

�������� ��=+ E-1/

��������� ���+ ,-C+ ..-.,+ 1F-1.�����+ ,-C

���=��� 4��+ .E-..+ .E-.3

��������� �����������+ .C-..

��������+ 1F-..?9+ 1F-.3+ 11-.C

����#����� �G��������+ .-.3

����#����� �������+ .-.3+ 3-1/

&�'+ 1-/

���������� ������+ 1.-,+ 1.-1C+ 11-1.

�������� �$�+ .-C+ E-33

�����4���+ E-./H<@89;+ 12-.,H?�@)(9+ 12-.,+ 12-.CH9@*<@89;+ 12-.,H6@I'@89*+ 12-.,+ 12-.CH6@I*B)(+ 1.-13H*B)(+ 1.-.3+ 11-C�����+ 12-1/��!������+ E-.3�G����� �����+ 12-.,

:$*���� ��� ����G

:?9&6BJ?9*(K(6+ 1.-./

4��+ .E-C

:��� �������+ 13-,+ 13-.3

4��������+ .C-3,+ .C-3C+ .C-2.�������+ .C-3,

:*?*5( ������+ '-.,

4���"�� �������+ .C-.C

4����K+ .C-3C�����+ .C-3C���� ?��+ .C-3C���� @��+ .C-3C���� @0��+ .C-3CL������ :���� :��+ .C-1.

Page 300: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

'� �����+ .C-23

��������� ��=+ E-1/

'�������� )�����+ 2-,

�#������� !������+ 3-C

�#������� ������� ����#���+ 1-1.

'M('N ���������+ E-13+ C-./+ C-13

���4��������+ .C-2.���������+ 1.-23��0������+ 1.-2/��4������+ .C-3,+ 1.-23+ 1/-..������+ 1.-2/�������� �#���#+ .C-3C�������+ .C-3,+ .C-23

�� ���+ 1.-2.

����+ ?-..

���� ����+ .-1.+ 1-,+ .2-..��� �� ���� #������

'@58A9 ������+ .-2/!���� ��� �������+ .-2C

���� ���������+ C-.,'M('N+ C-13<@6(?K9 N(B+ C-1.9@* 9855+ C-.C)6?A&6B N(B+ C-1.89?78(+ C-.C

���� #������+ .-..

������ !��+ '-./

������+ 1.-23��������+ 1.-1/

'@AA(9* ������+ .1-1.

'@AA?* ������+ 12-1,

'@AA?* ���������+ ..-3,+ ..-2.+ 11-1,

�������� ������� ��� ������

�����+ .C-3.+ 1F-,�����+ .C-1C

������� ������= ��=+ E-1/

������ ������= ��=+ E-1/

����������� ������+ .-13

�������+ 13-1/

�������� ��������� ��� ?< ���������

'@9�*&9* ��=>��+ 1.-,

���������� ��� 'M('N ����������<@6(?K9 N(B ���������� 9@* 9855���������� )6?A&6B N(B ����������89?78( ���������

����������+ C-./����+ C-.,���� ��������=+ E-13����+ E-13�����=+ E-13��!�������+ E-13����"��!����+ E-13

��4�+ C-.,

���� ���������+ .E-/+ 13-/?< ���������+ �=���G+ 13-,�+ 13-.,

��0����� !������+ 3-33

'@89* !������+ /-..

'6(&*( <89'*?@9 ������+ 1F-,6(*869 ���������+ 1F-.,

'6(&*( ?9;(O ������+ ./-.3

'6(&*( )6@'(;86( ������+ 1F-,

'6(&*( �(78(9'( ������+ .3-,

'6(&*( �B9@9BA ������+ .D-1/

'6(&*( *&:5( ������+ C-,+ C-1/��4����=+ C-3.

'6(&*( 8�(6 ������+ .D-,

'6(&*( L?(I ������+ .2-,I?*M 'M('N @)*?@9 �����+ .2-.,I?*M 6(&; @95B ����+ .2-.C

'�� '����+ .C-.3

'866L&5+ C-C+ .3-.3

�����+ 11-13+ 12-/�����4���+ 12-1/�G�����+ 11-,+ 11-./+ 12-/+ 12-,+ 12-1.�����4����+ 12-.,�����+ 12-./'86�@6 ���������+ 12-C

Page 301: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��������+ 12-C<(*'M ���������+ 12-.3!���#���+ �=���G+ 12-.3<@6 8);&*( �����+ 12-1,������+ 12-..+ 12-13IM(6( '866(9* @< �����+ 12-1,

<@6 �+ 12-1/�������+ 11-13+ 12-/

����� <@6 �� ��� �����

'86�@6 ���������� ��� �����

���# �"�+ ..-.,

���� ���� ������� �;'5�+ ?-1/+ C-,+..-3/+ 11-/

&5*(6 8�(6 ������+ .D-.3'6(&*( 6@5( ������+ .D-..'6(&*( �B9@9BA ������+ .D-1/'6(&*( 8�(6 ������+ .D-,;6@) �B9@9BA ������+ .D-1,K6&9* ������+ .D-./6(L@N( ������+ .D-13

���� ��!������ ������� �;;5�+ ?-1/+ C-,+..-3/+ .C-1/

&5*(6 *&:5( ������+ .1-/'@AA(9* ������+ .1-/'6(&*( *&:5( ������+ C-,;6@) *&:5( ������+ .1-.,6(9&A( ������+ .1-/*689'&*( ������+ .1-/

���� ��������=+ C-.,+ C-33+ .F-/;?'*J'@58A9�+ .F-C;?'*?@9&6B+ .F-C���0�����+ .D-1.8�(6J'@9�J'@58A9�+ .F-./+ .1-.38�(6J'@9�*6&?9*�+ .F-.3+ .1-.38�(6J?9;J'@58A9�+ ./-.,8�(6J?9;(O(�+ ./-.,8�(6J@:P('*�+ .F-C+ .3-..8�(6J�(78(9'(�+ .3-..8�(6JL?(I�+ .2-1.

���� ��������= ����������+ ?-./+ E-13

���� ���������� ������� �;A5�+ ?-1/+..-/+ ..-3/+ 11-/+ 11-13

;(5(*( ���������+ ..-1C?9�(6* ������+ ..-,8);&*( ���������+ ..-1.0��>+ .2-./+ .2-.C

����4���+ ?-C

����4��� ������+ E-/��4� �������� �#���+ E-1C

����4��� �������=+ .D-/

;���4��� *������ �����+ .C-/+ .C-C

�����=��+ C-.3+ 1.-C:?9&6BJ?9*(K(6+ 1.-./�������+ 1.-./��0�����+ 1.-3C���������+ 12-13�����+ 1.-C

���� !���� �������+ 3-3,

���� !������+ 3-1,

;:A�J�75 �������+ 11-/

;'5� ��� ���� ���� �������

;;5� ��� ���� ��!������ �������

��4�� �����+ .C-33+ .C-3/+ .C-3,

��������0� ������+ .E-C+ 1.-/

;(<&85* ��=>��+ C-,+ C-C+ .1-,+ 1.-,

��!��� 0���+ 11-.C

;(<?9( ������+ ,-./

;(5(*( ���������+ ..-1C+ 11-.C

;(�'+ 1-/

;(�'6?:( ������+ .-3C+ C-33+ .F-.3

;?�*?9'* ��=>��+ .-3.

;A5� ��� ���� ��!������ �������

;6@) ?9;(O ������+ ./-.C

;6@) �(78(9'( ������+ .3-.C

;6@) �B9@9BA ������+ .D-1,

;6@) *&:5( ������+ .1-.,'&�'&;( '@9�*6&?9*� ����+ .1-.,

;6@) L?(I ������+ .2-13

Page 302: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

;8&5 ��4�+ 3-13

����= ������ ����+ ..-C

�����=+ E-./��!������+ E-.3

�����= �������#�� ���+ E-.3+ E-1C�����4���+ E-.3�����=+ E-.3�����Q����+ E-1.�������#��+ E-.3

�������+ 2-..

���� #������� ��� �G������"#������������

�G������+ .E-C+ 11-.3+ 11-./+ 12-..+ 1/-/?9L&5?;J'86�@6+ 12-./+ 1/-..9@J;&*&J<@89;+ 11-./+ 11-.,+ 1/-/+

1/-..��"�����!���� @����, ���0�� ����+

1/-,+ 1/-./�����!���� @����, ���0�� ����+ 1/-,+

1/-..����������+ 1/-/+ 1/-1.6&?�( ���������+ 1/-/+ 1/-.,�75'@;(+ 1/-.C�75(66A+ 1/-.C*@@JA&9BJ6@I�+ 11-./+ 11-.,+ 1/-..��������+ 1/-/�=���G+ 1/-C

����"��!����+ 1/-,+ 1/-.,IM(9 @*M(6� �����+ 1/-C+ 1/-.C

�G������"#������ ������+ .E-C+ 1F-/+1.-/+ 1/-/+ 1/-C

�G�����4� ������+ .E-C+ 1.-/+ 1/-/

(O('8*( ������+ 1F-1.

(O?* ���������� ��� �

�G���+ ������ ����+ .C-1C

<(*'M ���������� ��� �����

!���+ ?-..

!���� ��� :*?*5( ������

<@6 8);&*( �����+ 12-1,

!����� ��=+ ?-..+ E-1,+ E-3,

<@6(?K9 N(B ���������+ E-13+ C-./+ C-1.+C-3.

@9 ;(5(*( '&�'&;(+ C-13

!������+ 3-/+ .E-.3+ 1F-/+ 11-13�#�������+ 3-C'@9'&*+ 3-C?9?*'&)+ 3-C5(9K*M+ 3-C5@I(6+ 3-C9L5+ 3-C�8:�*6+ 3-C8))(6+ 3-C

��0�����+ 3-33��� �� ���� !���� �������*@J'M&6+ 3-33+ 3-3/+ 3-2/*@J;&*(+ 3-33+ 3-2C*@J98A:(6+ 3-33+ 3-2C

����+ 3-1,&;;JA@9*M�+ 3-1,5&�*J;&B+ 3-1,A@9*M�J:(*I((9+ 3-1,9(O*J;&B+ 3-1,6@89;+ 3-1,*689'+ 3-1,

����+ /-/&LK+ /-,'@89*+ /-,A&O+ /-,A?9+ /-,�*;;(L+ /-,�8A+ /-,L&6?&9'(+ /-,

�� �75 ����������+ 1F-1/��0����+ 1F-1/������ �>+ 3-/�������+ 3-/.���4��+ 3-.,A@;+ 3-.,6@89;+ 3-.,*689'+ 3-.,

9L5+ .-1C����� �>+ 3-/+ 3-,�75+ 1F-./�75'@;(+ 1/-.C

Page 303: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

�75(66A+ 1/-.C��������+ 1F-13�=���G+ 1F-.,�B�;&*(+ 3-13+ 3-1/*@J;&*(+ ..-.3����"��!����+ 1F-./

K 4����+ .C-3C

K6&9* ������+ .D-C4���� ���0�����+ .D-./)8:5?' ��=>��+ .D-.CI?*M K6&9* @)*?@9 �����+ .D-.C

K6&9* 6@5( ������+ .D-..

K6@8) :B �����+ /-.3+ /-.C+ /-13

���� !������+ /-/��4����=+ D-.3

M&L?9K �����+ /-1.+ /-1/���� !������+ /-1/

#������ ��� **?*5( ������

#��'�� '����+ .C-.3����+ .C-C7���� *��+ .C-..

������!���+ .E-/+ 1F-13+ 1.-,+ 1.-1/+ 11-C+11-1.+ 1/-/

?< ���������+ 13-/������+ 13-..�=���G� ��� ���� ���������

?9 ���+ 1F-..

?9 @8* ���+ 1F-..+ 1F-.C

����G+ ./-/:$*���+ ./-/+ ./-C�����������+ ./-..'6(&*( ?9;(O ������+ ./-.3

;6@) ?9;(O ������+ ./-.C���������+ ./-./��"������+ ./-..�����Q����+ ./-,6@I?;+ ./-C����� ����+ ./-..89?78(+ C-.C+ C-1.+ ./-..

?9�(6* ���������+ ..-,+ 11-.C��4����=+ ..-.C

����������+ .E-,

?����������+ .C-C+ .C-13

?���������� ����+ .C-13+ .C-1/

?9*@ �����+ 11-,+ 11-C+ 12-C+ 12-.3

?9L&5?;J'86�@6 �G������+ 12-./

���'�������� )�����+ 2-,�������+ 2-..��"�������+ 2-.C����+ 2-1.��! ���+ 2-1/�����+ 2-C��4� ����+ 2-.,��4� ���!�G+ 2-.3IM(6( �����+ 2-C

��� �������+ 2-/

�G��� ����+ 1.-1/

�4���=+ .C-.C+ .C-1.�����#��+ .C-.C

5?N( ������+ 1-1.

�����+ .-1/+ 1.-1/

���� �������+ 13-.3

������ !��+ ,-.C+ '-..

�+ 13-.,4����+ 13-/�=���G+ 13-.,

����� <@6+ 12-1/

Page 304: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

(O?* ���������+ 13-/+ 13-.,<@6+ 13-/�=���G+ 13-1.

�4��+ 13-1,������+ 13-1,IM?5(+ 13-/�=���G+ 13-1/

>��# ������+ 12-.,+ 12-.C

���� ���������+ 13-/

���?9+ 1F-..?9 @8*+ 1F-..@8*+ 1F-..

���� ��� �����= �������#�� ���

�������=+ .E-/

������ �> ��4����=+ D-.,

������ ���������+ C-..

������ ����+ C-..

������ 4��+ 1.-1,

������� !�������� ��� !������

9(O*L&5+ C-C+ .3-.3

9@J;&*&J<@89; �G������� ����G������

���+ .C-1.

�����Q����+ E-1.

9@* 9855 ���������+ .-1,+ E-1/+ E-33+C-./+ C-.C+ C-3.+ C-33+ .1-,

9@* 9855 ��=>��+ 1.-,+ 1.-.3

9855 ��=>��+ ..-C

�� 0���+ ?-..+ .-1,+ 1-1/+ E-1,+ 1.-,

���4�� !������+ 3-.,

9L5 !������+ .-1C

@4���� 9�0�����+ .C-/+ .C-C+ .C-./+ .C-1,+.C-3,

@9 ;(5(*( '&�'&;(� ��� <@6(?K9 N(B���������

@)(9 ������ ��� �����

������+ 1.-3/&9;+ 1-1,:(*I((9+ 1-.C��������+ 1-..+ 1-./?9+ 1-.C?� 9855+ 1-1/5?N(+ 1-1.H+ 1-1.J+ 1-1.(�'&)( ����+ 1-13

����+ 1-./+ 13-.3@6+ 1-1,�75+ 1-./

������ ����������+ .-.,

@����, ���0��+ ?-.C

@6;(6 :B �����+ 1-/��� �� �(5('* ���������

@8* ���+ 1F-..+ 1F-.C

���� ���+ 2-1.

���� ��� ������ �����+ 2-1.

�������+ .E-..+ 1F-/

���������+ ,-1.+ 12-13+ 12-1/�����+ 1F-..+ 1F-1.!���+ 1F-..��+ .C-23����+ 1F-..��4��������+ 1F-1.�=���G+ 1F-C

����>��+ .D-.3

)5R�75+ ?-.C+ ?-13+ .E-/+ .E-./

)5R�75 4��+ �������+ 1.-1,

)5R�75 ?����������� ��� ?����������

Page 305: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

)5R�75 �����+ 1.-.C+ 11-,+ 11-..+ 12-1.+12-1/

��������+ 1.-1.�=���G+ 1.-1.

)5R�75 ��4�+ 1.-./��������+ 1.-.,�=���G+ 1.-.,

����4���=+ .E-,

������ (O'()*?@9J?9?*+ 1/-./

����������+ 1-1C

������= ��=+ ?-..+ E-1/+ E-1,

)6?A&6B N(B ���������+ .-1,+ E-13+ C-./+C-1.+ .1-./

����G+ ./-/

)6?A&6B N(B ����G+ .1-./

���0����+ C-,+ .F-/+ .D-/4����+ .D-/�=����+ .D-/

��������+ .E-.3+ 1F-/�=���G+ 1F-C

)������� :�����+ .E-.,+ .C-/+ 1F-,+11-1,+ 1/-..+ 1/-1.

������ ��������+ .E-..

������ ����+ .C-/+ .C-.C+ .C-1C+ 1F-/

)����� 8��� �����+ .C-/+ .C-C+ .C-1,

���������'866L&5+ C-135(L(5+ C-139(O*L&5+ C-136@I98A+ C-13

)8:5?' ��=>��+ .D-.C

7���� *��+ .C-..

������� �������4�+ .-1.+ 1.-1/�����+ .-1/+ 1-.3+ ,-..+ ,-.,+ ..-,+

..-./+ 1.-1/+ 1.-3.

6&?�( ���������� ��� �G������

�������0� �������#��+ E-.,+ E-.C

��!������� ��������= ���������� ���<@6(?K9 N(B ���������

������� ����4���+ ?-C

�������#��+ E-.,��!������+ E-.3���="�"���=+ E-.C���="�"��+ E-.C+ E-3,��"�"��+ E-.C+ E-3,�������0�+ E-.,

6(9&A( ������+ .1-.C

6���� 4����+ .C-3C

6(*869 ���������+ 1F-.,

6(L@N( ������+ .D-13

��+ .D-/+ .D-..

6@55:&'N ���������+ ..-3,+ ..-23+ 11-1,

�>+ ?-..

6@I?;+ ./-C+ 12-1.+ 12-1,

�&L()@?9* ���������+ ..-3,+ ..-2/+ 11-1C

��#���+ C-C

����+ 1.-1,

������ !��+ ,-1.+ C-1/+ '-./+ '-.C

�����#+ .C-1.

�������=+ .D-/��+ .D-/

�(5('* ������� ��� �(5('* ���������

�(5('* ���������+ ..-..+ 12-/4���� ����=+ .-/<6@A �����+ .-CK6@8) :B �����+ /-.3���������+ .-,M&L?9K �����+ /-1/?9*@ �����+ 11-,@6;(6 :B �����+ 1-/

Page 306: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

���� ���+ 2-1.����+ .-,�(5('* �����+ .-C+ 11-C����� ���+ 2-C�=���G+ 11-,IM(6( �����+ 1-..

��! ���+ 2-1/

������ ���+ 11-,

��������+ 1F-.3+ 11-.C&5*(6 �(78(9'( ������+ .3-.,���#�+ .3-./'6(&*( �(78(9'( ������+ .3-,;6@) �(78(9'( ������+ .3-.C����+ .3-./

�(* ������+ '-..

�(* L(6?<B ������+ ,-C

����� ���+ 2-C

��� ����� ��� @6;(6 :B �����

����� ����+ .C-13

�75+ .E-/+ '-C

�75 4�!!��+ .-,+ .-2.

�75 ������+ ?-.3+ ?-13+ .-3/

�75 ����� �����4����+ 11-13�75H<@89;+ 11-13�75H?�@)(9+ 11-13�75H9@*<@89;+ 11-13�75H6@I'@89*+ 11-13

�75 !������+ 1F-./+ 1.-3,��0�����+ 1.-3C�B�;&*(+ 3-13+ 3-1/+ 1F-.3+ 11-.C8�(6+ 1F-.3+ 11-.C

�75 ���������+ 11-/

�75$)��+ ?-13+ .-3/+ 1F-,+ 1F-1.+ 1/-1.+'-C

������� �������+ .-2.!�� �������+ .-23!���� �������+ '-./���������+ ,-1.�(* ������+ '-..

�75'@;( !������+ 1/-.C

�75(66A !������+ 1/-.C

�����+ .C-.C

����� ���+ .C-..+ .C-23

��������� �0� �4���+ ..-2,

���� ?�� 4����+ .C-3C

���� @�� 4����+ .C-3C

���� @0�� 4����+ .C-3C

����� !������+ .E-..

����� ��������+ .E-..

����� ������ ����+ .C-33

����� )����� 8��� �����+ .C-/+ .C-C+.C-3.

����� ��4�������+ 1F-/

��4������+ .E-.3+ .C-,��� �� !������� �����������������+ 1F-/��������+ 1F-,��0����+ 1F-1.

��4����=+ .2-,'6(&*( *&:5(+ C-3.M&L?9K �����+ D-.C?9�(6* ���������+ ..-.C������ �>+ D-.,����� �>+ D-..8);&*( ���������+ ..-1.IM(6( �����+ D-.C

��4�������� 0����4�+ ..-./

�=���G+ ����+ 1.-1/

�B�;&*(+ C-C+ C-13+ ..-..��� �� �75 !������

�=���� ��0������ �=��+ ?-.,+ E-,

�=���� ���0����+ .D-,

��4�+ ?-..+ .-/&5*(6 *&:5( ������+ .1-/'6(&*( �B9@9BA ������+ .D-1/'6(&*( *&:5( ������+ C-,;6@) *&:5( ������+ .1-.,���������+ ?-.3

��4� ����+ 2-.,

Page 307: Introduction to Oracle(SQL & PLSQL Using Procedure Builder) Volume Four Participant Guide

��4� ���������+ C-.,'M('N+ C-13<@6(?K9 N(B+ C-1.)6?A&6B N(B+ C-1.89?78(+ C-.C

��4� �������� �#���+ E-1C+ E-33+ C-1/

��4� ���!�G+ 2-.3

��4��+ C-/

*(O*J?@ �������+ 1F-13

*@J'M&6+ 3-3/+ 3-2/

*@J;&*(+ 3-2C

*@J;&*( !������+ ..-.3

*@J98A:(6+ 3-2C

*@@JA&9BJ6@I� �G������� ����G������

����������+ ..-/+ ..-3/+ 12-1,

���������� ����+ 11-1,

*689'&*( *&:5( ������+ .1-.C

**?*5( ������+ '-.,

8?;+ C-13��� �� ������ ������!���

89;(<?9( ������+ ,-.C

89?78( ���������+ E-1/+ C-./+ C-.C+ .1-./����G+ ./-/

������ ������!���+ E-./+ E-.C+ E-3/���4�� �=�4 � �+ E-./+ E-3/

89?78( ����G+ C-.C+ C-1.+ .1-./

������ ��=+ E-1/+ E-1,

8);&*( ���������+ ..-1.+ 11-.C+ 11-1.

8�(6+ C-C+ C-13

8�(6(9L+ C-13

8�(6?;+ ..-..

0����4�+ 1.-/+ 12-C4���+ 1F-1.#��+ 1.-2.+ 12-13�����+ 12-..��+ .C-23�����+ 1.-C

L������ :���� :��+ .C-1.

0��>+ .2-/����G+ .2-C+ .2-.3'6(&*( L?(I ������+ .2-,;6@) L?(I ������+ .2-13�����+ .2-C

IM(9 @*M(6� ������ ��� �G������

IM(6( �����+ 1-..+ /-1.+ 11-,+ 11-.3+11-1.

��� �� ���;(5(*( ���������+ ..-1C8);&*( ���������+ ..-1/

IM(6( '866(9* @< �����+ 12-1,

>������ �����#+ 1-1.