Sie sind auf Seite 1von 307

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Volume Four S Participant Guide

Edition 1.1 M03992 T1001E11

Authors Neena Kochhar Debby Kramer

Copyright EOracle Corporation, 1992, 1996. All rights reserved. This documentation contains proprietary information of Oracle Corporation; it is provided under a license agreement containing restrictions on use and disclo sure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the fol lowing legend is applicable: Restricted Rights Legend Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights soft ware under Federal law, and as set forth in subparagraph (c) (1) (ii) of DFARS 252.2277013, Rights in Technical Data and Computer Software (October 1988). This material or any portion of it may not be copied in any form or by any means without the express prior written permission of the Worldwide Education Services group of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties. If this documentation is delivered to a U.S. Government Agency not within the De partment of Defense, then it is delivered with Restricted Rights," as defined in FAR 52.22714, Rights in DataGeneral, including Alternate III (June 1987). The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Worldwide Education Services, Oracle Corporation, 500 Oracle Parkway, Box 659806, Red wood Shores, CA 94065. Oracle Corporation does not warrant that this document is error free. SQL*Plus, PL/SQL, Procedure Builder, Developer/2000, Oracle7 Server, Oracle Server, Discoverer/2000, and Designer/2000 are trademarks or registered trade marks of Oracle Corporation. All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Technical Contributors and Reviewers Christian Bauwens Debra Bowman Lenny Brunson Jackie Collins Ralf Durben Brian Fry Anthony Holbrook Karlene Jensen Sarah Jones Glenn Maslen Sundar Nagarathnam Sandra Schrick Ulrike Schwinn Rosemarie Truman Jenny Tsai Laura Van Deusen

Publishers Stephanie Jones Kimberly Lee Jennifer Robertson Mark Turangan

A
Practice Solutions

A2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Preface
There is often more than one way to achieve any result in SQL. Where possible, the alternatives 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 the database level. For more information, see Oracle7 Server SQL Reference, Release 7.3 and Oracle7 Server Administrators Guide.

Practice Solutions

A3

Practice 1 Solutions
1.

2.

3.

SQL commands are always held in a buffer. " True SQL*Plus commands assist with querying data. " False SQL*Plus commands allow you to format resulting data and control files. Only SQL accesses the database. Show the structure of the S_DEPT table. Select all information from the S_DEPT table. SQL> DESCRIBE s_dept Name ---------------------------ID NAME REGION_ID Null? -------NOT NULL NOT NULL Type ---NUMBER(7) VARCHAR2(25) NUMBER(7)

SQL> SELECT 2 FROM

* s_dept;

ID --------10 31 32 33 34 35 41 42 43 44 45 50

NAME REGION_ID ------------------------- --------Finance 1 Sales 1 Sales 2 Sales 3 Sales 4 Sales 5 Operations 1 Operations 2 Operations 3 Operations 4 Operations 5 Administration 1

12 rows selected.

A4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 1 Solutions
4.

continued

Show the structure of the S_CUSTOMER table. Using this table, perform the following actions: SQL> DESCRIBE s_customer Name -------------------------ID NAME PHONE ADDRESS CITY STATE COUNTRY ZIP_CODE CREDIT_RATING SALES_REP_ID REGION_ID COMMENTS
a.

Null? -------NOT NULL NOT NULL

Type ---NUMBER(7) VARCHAR2(50) VARCHAR2(25) VARCHAR2(400) VARCHAR2(30) VARCHAR2(20) VARCHAR2(30) VARCHAR2(75) VARCHAR2(9) NUMBER(7) NUMBER(7) VARCHAR2(255)

Retrieve all information from the S_CUSTOMER table. SQL> SELECT 2 FROM * s_customer;

Continued

Practice Solutions

A5

Practice 1 Solutions
4.continued b.

continued

Display the name and phone number for each customer. SQL> SELECT 2 FROM name, phone s_customer;

NAME ----------------------------------Unisports Simms Atheletics Delhi Sports Womansport Kams Sporting Goods Sportique Sweet Rock Sports Muench Sports Beisbol Si! Futbol Sonora Kuhns Sports Hamada Sport Big Johns Sports Emporium Ojibway Retail Sporta Russia 15 rows selected.

PHONE -------------55-2066101 81-20101 91-10351 1-206-104-0103 852-3692888 33-2257201 234-6036201 49-527454 809-352689 52-404562 42-111292 20-1209211 1-415-555-6281 1-716-555-7171 7-3892456

Continued

A6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 1 Solutions
4.continued c.

continued

Display the phone number and name for each customer, with phone number appearing first. SQL> SELECT 2 FROM phone, name s_customer;

PHONE -------------------55-2066101 81-20101 91-10351 1-206-104-0103 852-3692888 33-2257201 234-6036201 49-527454 809-352689 52-404562 42-111292 20-1209211 1-415-555-6281 1-716-555-7171 7-3892456 15 rows selected.

NAME ------------------------Unisports Simms Atheletics Delhi Sports Womansport Kams Sporting Goods Sportique Sweet Rock Sports Muench Sports Beisbol Si! Futbol Sonora Kuhns Sports Hamada Sport Big Johns Sports Emporium Ojibway Retail Sporta Russia

Practice Solutions

A7

Practice 2 Solutions
1.

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


"

False

2.

This SELECT statement will execute successfully. " True


SQL> SELECT 2 FROM 3 WHERE last_name, title, salary Ann_sal s_emp last_name = Dancs;

3.

This SELECT statement will execute successfully.


"

True SQL> SELECT 2 FROM 3 WHERE * s_emp salary*12 = 9600;

4.

There are four coding errors in this statement. Can you identify them? SQL> 2 3 4 5
" "

SELECT FROM WHERE AND

id, last_name, salary x 12 ANNUAL SALARY s_emp sal > 3000 start_date LIKE %84;

No SAL column in existence (WHERE clause). The ANNUAL SALARY alias cannot include spaces. Alias should read ANNUAL_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 single quotation marks. The value should read %84 in line 5.

" "

A8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2 Solutions
5.

continued

Use the S_CUSTOMER table to perform the following actions.


a.

Create a query to display the name, customer number, and credit rating for all companies represented by sales representative 11. Save your SQL statement to a file named p2q5. SQL> 2 3 4 SQL> SELECT FROM WHERE name, id, credit_rating s_customer sales_rep_id = 11

SAVE p2q5

Created file p2q5


b.

Run your query in the file p2q5. SQL> START p2q5 NAME ID CREDIT_RA ------------------------------ --------- --------Womansport 204 EXCELLENT Beisbol Si! 209 EXCELLENT Big Johns Sports Emporium 213 EXCELLENT Ojibway Retail 214 POOR

Continued

Practice Solutions

A9

Practice 2 Solutions
5.continued c.

continued

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 2 FROM 3* WHERE name, id, credit_rating s_customer sales_rep_id = 11

SQL> 1 SELECT name Company, id Company ID, SQL> i credit_rating Rating SQL> RUN 1 SELECT 2 3 FROM 4* WHERE name Company, id Company ID, credit_rating Rating s_customer sales_rep_id = 11

Company Company ID Rating ------------------------------ ---------- --------Womansport 204 EXCELLENT Beisbol Si! 209 EXCELLENT Big Johns Sports Emporium 213 EXCELLENT Ojibway Retail 214 POOR SQL> SAVE p2q5 REPLACE Wrote file p2q5

Continued

A10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2 Solutions
5.continued d.

continued

Retrieve p2q5 into the SQL buffer. Order the query results in descending order by customer number. Run your query.
SQL> GET p2q5 1 SELECT 2 3 FROM 4* WHERE name Company, id Company ID, credit_rating Rating s_customer sales_rep_id = 11

SQL> i ORDER BY 2 DESC SQL> / Company Company ID Rating ------------------------------ ---------- --------Ojibway Retail 214 POOR Big Johns Sports Emporium 213 EXCELLENT Beisbol Si! 209 EXCELLENT Womansport 204 EXCELLENT
6.

Show the structure of the S_EMP table. SQL> DESCRIBE s_emp Name -------------------------ID LAST_NAME FIRST_NAME USERID START_DATE COMMENTS MANAGER_ID TITLE DEPT_ID SALARY COMMISSION_PCT Null? -------NOT NULL NOT NULL Type ---NUMBER(7) VARCHAR2(25) VARCHAR2(25) NOT NULL VARCHAR2(8) DATE VARCHAR2(255) NUMBER(7) VARCHAR2(25) NUMBER(7) NUMBER(11,2) NUMBER(4,2)

Practice Solutions

A11

Practice 2 Solutions
6.continued a.

continued

Display the user name for employee 23. SQL> SELECT 2 FROM 3 WHERE userid s_emp id = 23;

USERID -------rpatel
b.

Display the first name, last name, and department number of the employees in departments 10 and 50 in alphabetical order of last name. Merge the first name and last name together, and title the column Employees. SQL> 2 3 4 5 SELECT first_name|| ||last_name Employees, dept_id FROM s_emp WHERE dept_id IN (10,50) ORDER BY last_name;

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

A12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2 Solutions
6.continued c.

continued

Display all employees whose last names contain an s.


"

This solution is not quite complete because names that contain a capital S do not appear in this list. In a later lesson, you will see how to change your query into a case-insensitive query. SQL> SELECT 2 FROM 3 WHERE first_name, last_name s_emp last_name like %s%;

FIRST_NAME ------------------------Carmen Andre Bela


d.

LAST_NAME -----------------------Velasquez Dumas Dancs

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> 2 3 4 5 SELECT FROM WHERE userid, start_date s_emp start_date BETWEEN 05-may-90 AND 26-may-91 ORDER BY start_date;

Continued

Practice Solutions

A13

Practice 2 Solutions
6d.continued

continued

USERID -------rmenchu cmagee rpatel echang murguhar anozaki ysedeghi mhavel bdancs sschwart amarkari

START_DAT --------14-MAY-90 14-MAY-90 17-OCT-90 30-NOV-90 18-JAN-91 09-FEB-91 18-FEB-91 27-FEB-91 17-MAR-91 09-MAY-91 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 not making between 1000 and 2500 per month. SQL> SELECT last_name, salary 2 FROM s_emp 3 WHERE salary NOT BETWEEN 1000 AND 2500; LAST_NAME SALARY ------------------------- --------Smith 940 Patel 795 Newman 750 Markarian 850 Chang 800 Patel 795 Dancs 860 7 rows selected.

Continued

A14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2 Solutions
7.continued b.

continued

List the last name and salary of employees who earn more than 1350 who are in department 31, 42, or 50. Label the last name column Employee Name, and label the salary column Monthly Salary. SQL> 2 3 4 5 SELECT FROM WHERE AND last_name Employee Name, salary Monthly Salary s_emp salary > 1350 dept_id IN (31, 42, 50);

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

Display the last name and start date of every employee who was hired in 1991. SQL> SELECT 2 FROM 3 WHERE last_name, start_date s_emp start_date LIKE %91;

Continued

Practice Solutions

A15

Practice 2 Solutions
7c.continued

continued

LAST_NAME ------------------------Nagayama Urguhart Havel Sedeghi Dumas Nozaki Patel Newman Markarian Dancs Schwartz 11 rows selected.
d.

START_DAT --------17-JUN-91 18-JAN-91 27-FEB-91 18-FEB-91 09-OCT-91 09-FEB-91 06-AUG-91 21-JUL-91 26-MAY-91 17-MAR-91 09-MAY-91

Display the full name of all employees with no manager. SQL> SELECT 2 FROM 3 WHERE first_name, last_name s_emp manager_id IS NULL;

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

A16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2 Solutions
8.

continued

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 2 FROM 3 WHERE name s_product name LIKE Pro%;

NAME ------------------------------------------------Pro Curling Bar Pro Ski Boot Pro Ski Pole Prostar 10 Pound Weight Prostar 100 Pound Weight Prostar 20 Pound Weight Prostar 50 Pound Weight Prostar 80 Pound Weight 8 rows selected. Continued

Practice Solutions

A17

Practice 2 Solutions
8.continued b.

continued

Display all product names and short descriptions for all descriptions containing the word bicycle.
"

Results have been formatted. name, short_desc s_product short_desc LIKE %bicycle%

SQL> SELECT 2 FROM 3 WHERE

NAME ------------------------Grand Prix Bicycle Himalaya Bicycle Grand Prix Bicycle Tires Himalaya Tires
c.

SHORT_DESC -------------------Road bicycle Mountain bicycle Road bicycle tires Mountain bicycle tires

Display all short descriptions. Compare the results from Exercise 10b. Did your response in Exercise 10b return all descriptions containing bicycle?
"

No, not all words containing bicycle were returned because the WHERE clause is case-sensitive. In a later lesson, you will see how to remove the case-sensitivity. SQL> SELECT short_desc 2 FROM s_product 3 ORDER BY 1;

Continued

A18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 2 Solutions
8c.continued

continued

SHORT_DESC --------------------------------------------Advanced ski boot Advanced ski pole Baseball Batting helmet Beginners ski boot Beginners ski pole Bicycle helmet Catchers glove Curling bar Eighty pound weight Elbow pads, pair Fifty pound weight Infielders glove Intermediate ski boot Intermediate ski pole Junior soccer ball Knee pads, pair Mountain bicycle Mountain bicycle tires One hundred pound weight Outfielders glove Road bicycle Road bicycle tires Straight bar Ten pound weight Thirty inch bat Thirty-six inch bat Thirty-two inch bat Tire pump Twenty pound weight Water bottle World cup net World cup soccer ball 33 rows selected.

Practice Solutions

A19

Practice 3 Solutions
1.

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


"

False Single row functions work for each row selected by the query and return one result per row. 2. You can use all of the arithmetic operators on date values. False Additional 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

A20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 3 Solutions
4.

continued

Display the employee number, last name, and salary increased by 15% and expressed as a whole number. SQL> SELECT 2 FROM id, last_name, ROUND(salary * 1.15) s_emp;

ID -----1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

LAST_NAME ROUND(SALARY*1.15) ------------ -----------------Velasquez 2875 Ngao 1668 Nagayama 1610 Quick-To-See 1668 Ropeburn 1783 Urguhart 1380 Menchu 1438 Biri 1265 Catchpole 1495 Havel 1503 Magee 1610 Giljum 1714 Sedeghi 1742 Nguyen 1754 Dumas 1668 Maduro 1610 Smith 1081 Nozaki 1380 Patel 914 Newman 863 Markarian 978 Chang 920 Patel 914 Dancs 989 Schwartz 1265

25 rows selected.

Practice Solutions

A21

Practice 3 Solutions
5.

continued

Display the employee last name and title in parentheses for all employees. The report should look like the output below. SQL> SELECT 2 3 FROM 4 ORDER BY last_name||(||INITCAP(title)||) EMPLOYEE s_emp 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.

A22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 3 Solutions
6.

continued

Display each employees last name, hire date, and salary review date, which is the first Monday after six months of service. Format the dates to appear in the format similar 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) REVIEW 5 FROM s_emp; Continued

Practice Solutions

A23

Practice 3 Solutions
6.continued

continued

LAST_NAME -----------Velasquez Ngao Nagayama Quick-To-See Ropeburn Urguhart Menchu Biri Catchpole Havel Magee Giljum Sedeghi Nguyen Dumas Maduro Smith Nozaki Patel Newman Markarian Chang Patel Dancs Schwartz

START_DAT --------03-MAR-90 08-MAR-90 17-JUN-91 07-APR-90 04-MAR-90 18-JAN-91 14-MAY-90 07-APR-90 09-FEB-92 27-FEB-91 14-MAY-90 18-JAN-92 18-FEB-91 22-JAN-92 09-OCT-91 07-FEB-92 08-MAR-90 09-FEB-91 06-AUG-91 21-JUL-91 26-MAY-91 30-NOV-90 17-OCT-90 17-MAR-91 09-MAY-91

REVIEW -----------------------------Tenth of September 1990 Tenth of September 1990 Twenty-Third of December 1991 Eighth of October 1990 Tenth of September 1990 Twenty-Second of July 1991 Nineteenth of November 1990 Eighth of October 1990 Tenth of August 1992 Second of September 1991 Nineteenth of November 1990 Twentieth of July 1992 Nineteenth of August 1991 Twenty-Seventh of July 1992 Thirteenth of April 1992 Tenth of August 1992 Tenth of September 1990 Twelfth of August 1991 Tenth of February 1992 Twenty-Seventh of January 1992 Second of December 1991 Third of June 1991 Twenty-Second of April 1991 Twenty-Third of September 1991 Eleventh of November 1991

25 rows selected.

A24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 3 Solutions
7.

continued

Display the product name for products that have ski in the name. SQL> SELECT 2 FROM 3 WHERE name s_product LOWER(name) LIKE %ski%;

NAME -------------------Ace Ski Boot Pro Ski Boot Bunny Ski Pole Ace Ski Pole Pro Ski Pole
8.

For each employee, calculate the number of months between today and the date the 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_WORKED 4 FROM s_emp 5 ORDER BY MONTHS_BETWEEN(SYSDATE, start_date);

Continued

Practice Solutions

A25

Practice 3 Solutions
8.continued

continued

LAST_NAME MONTHS_WORKED ------------ ------------Catchpole 46 Maduro 46 Nguyen 47 Giljum 47 Dumas 50 Patel 52 Newman 53 Nagayama 54 Markarian 55 Schwartz 55 Dancs 57 Havel 58 Sedeghi 58 Nozaki 58 Urguhart 59 Chang 61 Patel 62 Menchu 67 Magee 67 Quick-To-See 68 Biri 68 Ngao 69 Smith 69 Ropeburn 69 Velasquez 69 25 rows selected. Note: Your MONTHS_WORKED may differ from the solution because your SYSDATE may return a different value.

A26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 3 Solutions
9.

continued

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 2 3 FROM 4 ORDER BY last_name, start_date, TO_CHAR(start_date, DAY) DAY s_emp TO_CHAR(start_date-1, d);

LAST_NAME -----------Nagayama Menchu Sedeghi Magee Patel Havel Patel Nguyen Dumas Ngao Smith Schwartz Urguhart Chang Maduro Velasquez Quick-To-See Biri Nozaki Giljum Ropeburn Newman Dancs Markarian Catchpole

START_DAT --------17-JUN-91 14-MAY-90 18-FEB-91 14-MAY-90 06-AUG-91 27-FEB-91 17-OCT-90 22-JAN-92 09-OCT-91 08-MAR-90 08-MAR-90 09-MAY-91 18-JAN-91 30-NOV-90 07-FEB-92 03-MAR-90 07-APR-90 07-APR-90 09-FEB-91 18-JAN-92 04-MAR-90 21-JUL-91 17-MAR-91 26-MAY-91 09-FEB-92

DAY ---------MONDAY MONDAY MONDAY MONDAY TUESDAY WEDNESDAY WEDNESDAY WEDNESDAY WEDNESDAY THURSDAY THURSDAY THURSDAY FRIDAY FRIDAY FRIDAY SATURDAY SATURDAY SATURDAY SATURDAY SATURDAY SUNDAY SUNDAY SUNDAY SUNDAY SUNDAY

25 rows selected.

Practice Solutions

A27

Practice 3 Solutions
10.

continued

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.

A28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 4 Solutions
Use the S_EMP, S_DEPT, S_CUSTOMER, S_REGION, S_ORD, S_ITEM, and S_PRODUCT tables to complete the following exercises.
1.

Write a report containing each employees last name, department number, and name of their department. SQL> SELECT 2 3 FROM 4 WHERE s_emp.last_name, s_emp.dept_id, s_dept.name s_emp, s_dept s_emp.dept_id = s_dept.id;

Continued

Practice Solutions

A29

Practice 4 Solutions
1.continued

continued

LAST_NAME DEPT_ID NAME ------------ ------- -------------------Velasquez 50 Administration Ngao 41 Operations Nagayama 31 Sales Quick-To-See 10 Finance Ropeburn 50 Administration Urguhart 41 Operations Menchu 42 Operations Biri 43 Operations Catchpole 44 Operations Havel 45 Operations Magee 31 Sales Giljum 32 Sales Sedeghi 33 Sales Nguyen 34 Sales Dumas 35 Sales Maduro 41 Operations Smith 41 Operations Nozaki 42 Operations Patel 42 Operations Newman 43 Operations Markarian 43 Operations Chang 44 Operations Patel 34 Sales Dancs 45 Operations Schwartz 45 Operations 25 rows selected.

A30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 4 Solutions
2.

continued

Write a query to display the last name, department name, and region name of all employees who earn a commission.
"

Results have been formatted. SQL> 2 3 4 5 SELECT FROM WHERE AND AND e.last_name, d.name, r.name s_emp e, s_dept d, s_region r e.dept_id = d.id r.id = d.region_id e.commission_pct IS NOT NULL;

LAST_NAME -----------Magee Giljum Sedeghi Nguyen Dumas


3.

NAME -------------Sales Sales Sales Sales Sales

NAME -------------------North America South America Africa / Middle East Asia Europe

Display the employee name and department name for Smith. SQL> 2 3 4 SELECT FROM WHERE AND s_emp.last_name, s_dept.name s_emp, s_dept s_emp.dept_id = s_dept.id s_emp.last_name = Smith;

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

Practice Solutions

A31

Practice 4 Solutions
4.

continued

Display the product name, product number, and quantity ordered of all items in order number 101. Label the quantity column ORDERED. SQL> 2 3 4 5 6 SELECT s_product.name, s_product.id, s_item.quantity ORDERED s_product, s_item s_product.id = s_item.product_id s_item.ord_id = 101;

FROM WHERE AND

NAME --------------------------------Grand Prix Bicycle Tires Pro Curling Bar Prostar 10 Pound Weight Prostar 100 Pound Weight Major League Baseball Griffey Glove Cabrera Bat 7 rows selected.
5.

ID ORDERED ----- ------30421 15 40422 30 41010 20 41100 35 50169 40 50417 27 50530 50

Display the customer number and the last name of their sales representative. Order the list by last name. SQL> 2 3 4 SELECT FROM WHERE ORDER BY s_customer.id, s_emp.last_name s_emp, s_customer s_emp.id = s_customer.sales_rep_id s_emp.last_name;

Continued

A32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 4 Solutions
5.continued

continued

ID ----205 206 208 211 215 201 210 204 214 209 213 202 203 212

LAST_NAME --------------Dumas Dumas Dumas Dumas Dumas Giljum Giljum Magee Magee Magee Magee Nguyen Nguyen Sedeghi

14 rows selected.
6.

Display the customer number, customer name, and order number of all customers and their orders. Display the customer number and name, even if they have not placed an order. SQL> SELECT 2 3 4 FROM 5 WHERE 6 s_customer.id Customer ID, s_customer.name Customer Name, s_ord.id Order ID s_customer, s_ord s_customer.id = s_ord.customer_id (+);

Continued

Practice Solutions

A33

Practice 4 Solutions
6.continued

continued

Customer ID ----------201 202 203 204 204 205 206 207 208 208 209 210 210 211 212 213 214 215

Customer Name Order ID ------------------------------ ---------Unisports 97 Simms Atheletics 98 Delhi Sports 99 Womansport 100 Womansport 111 Kams Sporting Goods 101 Sportique 102 Sweet Rock Sports Muench Sports 103 Muench Sports 104 Beisbol Si! 105 Futbol Sonora 106 Futbol Sonora 112 Kuhns Sports 107 Hamada Sport 108 Big Johns Sports Emporium 109 Ojibway Retail 110 Sporta Russia

18 rows selected.
7.

Display all employees by last name name and employee number along with their manager s last name and manager number. SQL> SELECT 2 3 FROM 4 WHERE w.last_name EMP_NAME, w.id EMP_ID, m.last_name MGR_NAME, m.id MGR_ID s_emp w, s_emp m w.manager_id = m.id;

Continued

A34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 4 Solutions
7.continued

continued

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

Practice Solutions

A35

Practice 4 Solutions
8.

continued

Modify the solution to exercise 7 to also display Velasquez, who has no manager.
SQL> SELECT 2 3 4 FROM WHERE w.last_name Employee Name, w.id Employee ID, m.last_name Manager Name, m.id Manager ID s_emp w, s_emp m w.manager_id = m.id (+);

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

A36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 4 Solutions
9.

continued

Display all customers and the product number and quantities they ordered for those customers whose order totaled more than 100,000. SQL> 2 3 4 5 6 7 8 SELECT FROM WHERE AND AND AND c.name CUSTOMER, p.id PRODUCT_ID, i.quantity s_customer c, s_product p, s_item i, s_ord o c.id = o.customer_id o.id = i.ord_id i.product_id = p.id o.total > 100000;

Continued

Practice Solutions

A37

Practice 4 Solutions
9.continued

continued

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

A38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 5 Solutions
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 False Group functions ignore null values. If you want to include null values, use the NVL function. False The WHERE clause restricts rows prior to inclusion in a group calculation. True

b.

Group functions include nulls in calculations.


"

c.

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


"

d.

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

2.

Display the highest and lowest order totals in the S_ORD. Label the columns Highest and Lowest, respectively. SQL> SELECT 2 3 FROM MAX (total) Highest, MIN (total) Lowest s_ord;

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


3.

Write a query to display the minimum and maximum salary for each job type ordered alphabetically. SQL> SELECT 2 3 FROM 4 GROUP BY title JOB, MAX(salary) MAXIMUM, MIN(salary) MINIMUM s_emp title;

Continued

Practice Solutions

A39

Practice 5 Solutions
3.continued

continued

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

Determine the number of managers without listing them. SQL> SELECT 2 3 FROM COUNT(DISTINCT(manager_id)) Number of Managers s_emp;

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


5.

Display the number of line items in each order under each order number, labeled Number of Items. SQL> SELECT ord_id, COUNT(*) NUMBER OF ITEMS 2 FROM s_item 3 GROUP BY ord_id;

Continued

A40

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 5 Solutions
5.continued

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 that manager. Exclude any groups where the minimum salary is less than 1000. Sort the output by salary. SQL> 2 3 4 5 6 SELECT manager_id, MIN(salary) LOWEST PAID EMPLOYEE FROM s_emp GROUP BY manager_id HAVING MIN(salary) >= 1000 ORDER BY 2;

Continued

Practice Solutions

A41

Practice 5 Solutions
6.continued

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 2 FROM MAX(salary) - MIN (salary) DIFFERENCE s_emp;

DIFFERENCE ---------1750

A42

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 5 Solutions
If you have time, complete the following exercises.
8.

continued

Display the product number and number of times it was ordered, labeled Times Ordered. Only show those products that have been ordered at least three times. Order the data by the number of products ordered. SQL> 2 3 4 5 6 SELECT product_id, COUNT(ord_id) TIMES ORDERED FROM s_item GROUP BY product_id HAVING COUNT(ord_id) >= 3 ORDER BY COUNT(ord_id);

PRODUCT_ID ---------20106 20108 20201 20510 50273 30421 20512 30321 8 rows selected.
9.

TIMES ORDERED -------------3 3 3 3 3 3 3 4

Retrieve the region number, region name, and the number of departments within each region. SQL> 2 3 4 SELECT FROM WHERE GROUP BY r.id, r.name, COUNT(d.id) # OF DEPT s_dept d, s_region r d.region_id = r.id r.id, r.name;

Continued

Practice Solutions

A43

Practice 5 Solutions
9.continued

continued

ID ----1 2 3 4 5
10.

NAME # OF DEPT --------------------------- ---------------North America 4 South America 2 Africa / Middle East 2 Asia 2 Europe 2

Display the order number and total item count for each order of 100 or more items. For example, if order number 99 contains quantity 30 of one item, and quantity 75 of another item, then the total item count for that order is 105. SQL> 2 3 4 5 SELECT ord_id, SUM(quantity) TOTAL ITEM COUNT FROM s_item GROUP BY ord_id HAVING SUM(quantity) >= 100;

ORD_ID TOTAL ITEM COUNT ---------- ----------------97 1050 99 165 100 3100 101 217 102 145 106 392 107 332 108 321 109 3143 9 rows selected.

A44

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 5 Solutions
11.

continued

Display the customer name and the number of orders for each customer. SQL> 2 3 4 SELECT FROM WHERE GROUP BY c.name, COUNT(o.id) NUMBER OF ORDERS s_customer c, s_ord o c.id = o.customer_id c.name;

NAME NUMBER OF ORDERS -------------------------------- ----------------Beisbol Si! 1 Big Johns Sports Emporium 1 Delhi Sports 1 Futbol Sonora 2 Hamada Sport 1 Kams Sporting Goods 1 Kuhns Sports 1 Muench Sports 2 Simms Athletics 1 Ojibway Retail 1 Sportique 1 Unisports 1 Womansport 2 13 rows selected.

Practice Solutions

A45

Practice 6 Solutions
1.

Answer the following questions


a.

Which query runs first with a subquery?


"

Inner query runs first. The first query executes once.

b.

How many times does the first query run?


"

c.

You cannot use the equals (=) operator if the inner query returns more than one value.
"

i.
"

True If the answer is True, why and what operator should be used? The equals operator expects one value in return. Use the IN operator. If the answer is False, why?

ii. 2.

Display the first name, last name, and start date for all employees in the same department as Magee. SQL> SELECT first_name, last_name, start_date 2 FROM s_emp 3 WHERE dept_id = 4 (SELECT dept_id 5 FROM s_emp 6 WHERE last_name = Magee);

FIRST_NAME -------------------Midori Colin

LAST_NAME -------------------Nagayama Magee

START_DAT --------17-JUN-91 14-MAY-90

A46

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 6 Solutions
3.

continued

Display the employee number, first name, last name, and user name for all employees with salaries above the average salary. SQL> SELECT id, first_name, last_name, userid 2 FROM s_emp 3 WHERE salary > 4 (SELECT AVG(salary) 5 FROM s_emp);

ID ------1 2 3 4 5 9 10 11 12 13 14 15 16

FIRST_NAME --------------Carmen LaDoris Midori Mark Audry Antoinette Marta Colin Henry Yasmin Mai Andre Elena

LAST_NAME --------------Velasquez Ngao Nagayama Quick-To-See Ropeburn Catchpole Havel Magee Giljum Sedeghi Nguyen Dumas Maduro

USERID -------cvelasqu lngao mnagayam mquickto aropebur acatchpo mhavel cmagee hgiljum ysedeghi mnguyen adumas emaduro

13 rows selected.

Practice Solutions

A47

Practice 6 Solutions
4.

continued

Display last name, department number, and title for all employees assigned to region 1 or region 2. SQL> SELECT last_name, dept_id, title 2 FROM s_emp 3 WHERE dept_id IN 4 (SELECT id 5 FROM s_dept 6 WHERE region_id IN (1,2));

LAST_NAME DEPT_ID TITLE -------------------- --------- ------------------Velasquez 50 President Ngao 41 VP, Operations Nagayama 31 VP, Sales Quick-To-See 10 VP, Finance Ropeburn 50 VP, Administration Urguhart 41 Warehouse Manager Menchu 42 Warehouse Manager Magee 31 Sales Representative Giljum 32 Sales Representative Maduro 41 Stock Clerk Smith 41 Stock Clerk Nozaki 42 Stock Clerk Patel 42 Stock Clerk 13 rows selected.

A48

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 6 Solutions
5.

continued

Display the last name and salary for all employees that report to LaDoris Ngao. SQL> SELECT last_name, salary 2 FROM s_emp 3 WHERE manager_id = 4 (SELECT id 5 FROM s_emp 6 WHERE last_name = Ngao);

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

Practice Solutions

A49

Practice 6 Solutions
6.

continued

Display the employee number, first name, and last name for all employees with a salary above the average salary and that work with any employee with a last name that contains a t. SQL> 2 3 4 5 6 7 8 9 SELECT id, first_name, last_name FROM s_emp WHERE salary > (SELECT AVG(salary) FROM s_emp) AND dept_id IN (SELECT dept_id FROM s_emp WHERE UPPER(last_name) LIKE %T%);

ID ------4 14 2 16 9 10

FIRST_NAME -------------------Mark Mai LaDoris Elena Antoinette Marta

LAST_NAME ------------------Quick-To-See Nguyen Ngao Maduro Catchpole Havel

6 rows selected.

A50

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 6 Solutions
7.

continued

Display the customer number, customer name, customer rating, and sales representatives last name for all customers who are located in the North America region or have Nguyen as their sales representative.

SQL> 2 3 4 5 6 7 8 9 10

SELECT FROM WHERE AND

OR

c.id, c.name, c.credit_rating, e.last_name s_customer c, s_emp e c.sales_rep_id = e.id (c.region_id = (select id from s_region where name = North America) c.sales_rep_id = (select id from s_emp where last_name = Nguyen));

ID 202 203 204 209 213 214

NAME CREDIT_RA Simms Athletics POOR Delhi Sports GOOD Womansport EXCELLENT Beisbol Si! EXCELLENT Big Johns Sports Emporium EXCELLENT Ojibway Retail POOR

LAST_NAME Nguyen Nguyen Magee Magee Magee Magee

6 rows selected.

Practice Solutions

A51

Practice 6 Solutions
8.

continued

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

Results have been formatted. SQL> SELECT name, short_desc DESCRIPTION 2 FROM s_product 3 WHERE id NOT IN 4 (SELECT s_item.product_id 5 FROM s_item, s_ord 6 WHERE s_item.ord_id = s_ord.id 7 AND s_ord.date_ordered BETWEEN 8 01-SEP-92 AND 30-SEP-92);

NAME -----------------------Pro Ski Boot Bunny Ski Pole Pro Ski Pole Pro Curling Bar Prostar 10 Pound Weight Prostar 20 Pound Weight Prostar 50 Pound Weight Griffey Glove Cabrera Bat 9 rows selected.

DESCRIPTION ------------------------Advanced ski boot Beginners ski pole Advanced ski pole Curling bar Ten pound weight Twenty pound weight Fifty pound weight Outfielders glove Thirty inch bat

A52

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 6 Solutions
9.

continued

Display the customer name and credit rating for all customers of sales representative Andre Dumas. SQL> SELECT name, credit_rating 2 FROM s_customer 3 WHERE sales_rep_id = 4 (SELECT id 5 FROM s_emp 6 WHERE last_name = Dumas);

NAME -----------------------Kams Sporting Goods Sportique Muench Sports Kuhns Sports Sporta Russia

CREDIT_RA --------EXCELLENT EXCELLENT GOOD EXCELLENT POOR

Practice Solutions

A53

Practice 6 Solutions
10.

continued

Display each sales representatives last name in region 1 and region 2, their customers names and each customer s total sales orders. SQL> SELECT 2 3 FROM 4 WHERE 5 AND 6 AND 7 8 GROUP BY e.last_name, c.name, sum(o.total) Order Total s_emp e, s_customer c, s_ord o e.id = c.sales_rep_id c.id = o.customer_id e.dept_id in (select id from s_dept where region_id in (1,2)) e.last_name, c.name;

LAST_NAME NAME ORDER TOTAL Giljum Futbol Sonora 16184 Giljum Unisports 84000 Magee Beisbol Si! 2722.24 Magee Big Johns Sports Emporium 1020935 Magee Ojibway Retail 1539.13 Magee Womansport 603870 6 rows selected.

A54

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 7 Solutions
Determine whether the following statements are true.
1.

A single ampersand substitution variable prompts only once.


"

True However, if the variable is defined, then the single ampersand substitution variable will not prompt at all. In fact, it will pick up the value in the predefined variable. 2. The ACCEPT command is a SQL command.
"

False The ACCEPT command is a SQL*Plus command. It is issued at the SQL prompt.

Practice Solutions

A55

Practice 7 Solutions
3.

continued

The following questions use the S_EMP, S_CUSTOMER, and S_PRODUCT tables. Write a script file to display the user ID, first and last names concatenated together, and start dates of employees within a specified range. Prompt the user for the two ranges using the ACCEPT command. Use the format MM/DD/YY. Save the script file as p7q3.sql. SET ECHO OFF SET VERIFY OFF ACCEPT 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 A30 SELECT userid, first_name|| ||last_name employee, start_date FROM s_emp WHERE start_date BETWEEN TO_DATE(&low_date,MM/DD/YY) AND TO_DATE(&high_date,MM/DD/YY) / UNDEFINE low_date UNDEFINE high_date COLUMN employee CLEAR SET VERIFY ON SET ECHO ON

SQL> START p7q3 SET ECHO OFF Enter the low date range (MM/DD/YY): 09/01/91 Enter the high date range (MM/DD/YY): 09/01/92 USERID -------acatchpo hgiljum mnguyen adumas emaduro EMPLOYEE -----------------------------Antoinette Catchpole Henry Giljum Mai Nguyen Andre Dumas Elena Maduro START_DAT --------09-FEB-92 18-JAN-92 22-JAN-92 09-OCT-91 07-FEB-92

A56

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 7 Solutions
4.

continued

Write a script to search for customer names and numbers. The search condition should allow for case-insensitive name searches. Save the script file as p7q4.sql. Your result should look like the output below.
SET ECHO OFF ACCEPT p_customer PROMPT Please enter the customers name: COLUMN name HEADING CUSTOMER NAME FORMAT A40 SELECT id, name FROM s_customer WHERE UPPER(name) LIKE UPPER(%&p_customer%) / UNDEFINE p_customer COLUMN name CLEAR SET ECHO ON

"

Notice that the variable is between single quotation marks. Without the quotation marks, the operator would have to input the quotation marks at the prompt. SQL> START p7q4 SET ECHO OFF Please enter the customers name: sport ID -----201 203 204 205 206 207 208 211 212 213 215 CUSTOMER NAME ---------------------------------------Unisports Delhi Sports Womansport Kams Sporting Goods Sportique Sweet Rock Sports Muench Sports Kuhns Sports Hamada Sport Big Johns Sports Emporium Sporta Russia

11 rows selected.

Practice Solutions

A57

Practice 7 Solutions
5.

continued

Write a report containing the sales representative name, customer name, and each customer s total sales order. Prompt the user for a region number. Save the script as p7q5.sql.

SET ECHO OFF SET VERIFY OFF ACCEPT p_region NUMBER PROMPT Please enter a region number: COLUMN employee FORMAT A25 COLUMN customer FORMAT A30 COLUMN sales FORMAT $9,999,999 SELECT a.first_name|| ||a.last_name EMPLOYEE, b.name CUSTOMER, SUM(c.total) SALES FROM s_emp a, s_customer b, s_ord c WHERE a.id = b.sales_rep_id AND b.id = c.customer_id AND 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 CLEAR COLUMN customer CLEAR COLUMN employee CLEAR SET VERIFY ON SET ECHO ON

SQL> START p7q5


Please enter a region number: 1 EMPLOYEE ---------------------Colin Magee Colin Magee Colin Magee Colin Magee CUSTOMER --------------------------Beisbol Si! Big Johns Sports Emporium Ojibway Retail Womansport SALES ----------$2,722 $1,020,935 $1,539 $603,870

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

A58

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 9 Solutions
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 table constraint.

SQL> CREATE TABLE T_3000 2 (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 column constraint. Add (id) after PRIMARY KEY in line 9 because this is a table constraint. Change table name in line 1 because 1995_orders is an illegal table name. A table name must begin with a letter.

SQL> CREATE TABLE 1995_orders 2 (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);

Practice Solutions

A59

Practice 9 Solutions
2.

continued

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 the table. Confirm that the table is created. You will add data to the table in another lesson.

Table name: DEPARTMENT Column Name Key Type Nulls/ Unique FK Table FK Column Datatype Length
"

ID PK NN, U

NAME

NUMBER 7

CHAR 25

Script p9q2.sql contents. SET ECHO OFF CREATE 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? -------------------------- -------ID NOT NULL NAME Type ---NUMBER(7) VARCHAR2(25)

A60

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 9 Solutions
3.

continued

Create the EMPLOYEE table based on the table instance chart given below. Enter the syntax in a script p9q3.sql, then execute the script to create the table. Confirm that the table is created. You will add data to the table in another lesson. Table name: EMPLOYEE Column Name Key Type FK Table FK Column Datatype Length Continued NUMBER CHAR 7 25 CHAR 25 ID PK NN LAST_NAME FIRST_NAME DEPT_ID FK NN DEPARTMENT ID NUMBER 7

Nulls/ Unique NN, U

Practice Solutions

A61

Practice 9 Solutions
3.continued
"

continued

Script p9q3.sql contents. SET ECHO OFF CREATE 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 ID LAST_NAME FIRST_NAME DEPT_ID Null? NOT NULL NOT NULL NOT NULL Type NUMBER(7) VARCHAR2(25) VARCHAR2(25) NUMBER(7)

A62

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 10 Solutions
1.

Select all the views from the data dictionary pertaining to Table. You can adjust the column formats by using the SQL*Plus COLUMN command. SQL> SQL> SQL> 2 3 COLUMN TABLE_NAME FORMAT A22 COLUMN COMMENTS FORMAT A50 WORD_WRAPPED SELECT * FROM DICTIONARY WHERE LOWER(COMMENTS) LIKE %table%;

TABLE_NAME COMMENTS ----------------- -------------------------------ALL_CATALOG All tables, views, synonyms, sequences accessible to the user ALL_COL_COMMENTS Comments on columns of accessible tables and views ALL_CONSTRAINTS Constraint definitions on accessible tables ALL_INDEXES Descriptions of indexes on tables accessible to the user ALL_IND_COLUMNS COLUMNs comprising INDEXes on accessible TABLES ALL_TABLES Description of tables accessible to the user ALL_TAB_COLUMNS Columns of all tables, views and clusters ALL_TAB_COMMENTS Comments on tables and views accessible to the user ALL_TRIGGER_COLS Column usage in users triggers or in triggers on users tables USER_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

Practice Solutions

A63

Practice 10 Solutions
1.continued

continued

TABLE_NAME COMMENTS ----------------- -------------------------------USER_CATALOG Tables, Views, Synonyms and Sequences owned by the user USER_CLU_COLUMNS Mapping of table columns to cluster columns USER_COL_COMMENTS Comments on columns of users tables and views USER_CONSTRAINTS Constraint definitions on users own tables USER_FREE_SPACE Free extents in tablespaces accessible to the user USER_IND_COLUMNS COLUMNs comprising users INDEXes or on users TABLES USER_OBJ_AUDIT_OP Auditing options for users own TS tables and views USER_TABLES Description of the users own tables USER_TABLESPACES Description of accessible tablespaces USER_TAB_COLUMNS Columns of users tables, views and clusters USER_TAB_COMMENTS Comments on the tables and views owned by the user USER_TS_QUOTAS Tablespace quotas for the user AUDIT_ACTIONS Description table for audit trail action type codes. Maps action type numbers to action type names DICTIONARY Description of data dictionary tables and views DICT_COLUMNS Description of columns in data dictionary tables and views ROLE_TAB_PRIVS Table privileges granted to roles TABS Synonym for USER_TABLES 27 rows selected.

A64

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 10 Solutions
2.

continued

If a query is very lengthy, what SQL*Plus command can you set before you execute 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 tables you created in Practice 9, DEPARTMENT and EMPLOYEE tables. SQL> 2 3 4 5 SELECT FROM WHERE AND * user_objects object_type = TABLE object_name IN (EMPLOYEE,DEPARTMENT);

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

Practice Solutions

A65

Practice 10 Solutions
4.

continued

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

Script p10q4.sql contents. SET ECHO OFF REM SQL*Plus commands ACCEPT table PROMPT Table to view constraints: COLUMN constraint_name FORMAT A25 COLUMN search_condition FORMAT A25 COLUMN r_constraint_name FORMAT A20 REM SELECT statement to query the constraints SELECT constraint_name, constraint_type, search_condition, r_constraint_name FROM user_constraints WHERE table_name = UPPER(&table) / CLEAR COLUMN SET ECHO ON

SQL> START p10q4 Table to view constraints: department CONSTRAINT_NAME ------------------------SEARCH_CONDITION ------------------------DEPARTMENT_ID_PK C R_CONSTRAINT_NAME -------------------P

A66

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 10 Solutions
4.continued

continued

SQL> START p10q4 Table to view constraints: employee CONSTRAINT_NAME ------------------------SEARCH_CONDITION ------------------------EMPLOYEE_LAST_NAME_NN LAST_NAME IS NOT NULL EMPLOYEE_ID_PK C R_CONSTRAINT_NAME -------------------C

EMPLOYEE_DEPT_ID_FK EMPLOYEE_DEPT_ID_NN DEPT_ID IS NOT NULL C

R DEPARTMENT_ID_PK

Practice Solutions

A67

Practice 11 Solutions
1.

Insert data into the DEPARTMENT and EMPLOYEE tables.


a.

Describe the DEPARTMENT and EMPLOYEE tables to identify the column names. SQL> DESCRIBE department Name Null? -------------------------- -------ID NOT NULL NAME Type ---NUMBER(7) VARCHAR2(25)

SQL> DESCRIBE employee Name -------------------------ID LAST_NAME FIRST_NAME DEPT_ID


b.

Null? -------NOT NULL NOT NULL

Type ---NUMBER(7) VARCHAR2(25) VARCHAR2(25) NOT NULL NUMBER(7)

View the constraints on each table to identify the primary key and any other constraints. Execute the script p10q4.sql, which is a generic query to confirm constraints. SQL> START p10q4 Table to view constraints: department CONSTRAINT_NAME ------------------------SEARCH_CONDITION ------------------------DEPARTMENT_ID_PK C R_CONSTRAINT_NAME -------------------P

A68

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11 Solutions
1b.continued

continued

SQL> START p10q4 Table to view constraints: employee CONSTRAINT_NAME ------------------------SEARCH_CONDITION ------------------------EMPLOYEE_LAST_NAME_NN LAST_NAME IS NOT NULL EMPLOYEE_ID_PK C R_CONSTRAINT_NAME -------------------C

EMPLOYEE_DEPT_ID_FK

R DEPARTMENT_ID_PK

c.

Add a row of data to the DEPARTMENT table. The department number is 10 and the department name is Finance. Do not list the columns in the INSERT clause. SQL> INSERT INTO 2 VALUES 1 row created. department (10, Finance);

Practice Solutions

A69

Practice 11 Solutions
1.continued d.

continued

Add two rows of data to the EMPLOYEE table. Write a script named p11q1d.sql that prompts you for each column value. The first employee is Donna Smith in department number 10, and her employee number is 200. The second employee is Albert Jones in department number 54, and his employee number is 201. What was the result and why? SET ECHO OFF INSERT 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 OFF Enter value for first_name: Donna Enter value for last_name: Smith Enter value for department_number: 10 Enter value for employee_number: 200 1 row created.

A70

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11 Solutions
1d.continued

continued

SQL> START p11q1d SQL> SET ECHO OFF Enter value for first_name: Albert Enter value for last_name: Jones Enter value for department_number: 54 Enter value for employee_number: 201 INSERT 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 does not exist.

e.

Insert into the DEPARTMENT table department number 10 and department name of Marketing. What was the result and why? SQL> INSERT INTO 2 VALUES department (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 10 already exists.

Practice Solutions

A71

Practice 11 Solutions
1.continued f.

continued

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

A72

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11 Solutions
1.continued g.

continued

Write a script named p11q1g.sql to prompt the user to add the following rows to the DEPARTMENT table: Marketing as number 37; Sales as number 54; and Personnel as number 75. SET ECHO OFF INSERT INTO department (name, id) VALUES (&department_name,&id) / SET ECHO ON

SQL> START p11q1g SQL> SET ECHO OFF Enter value for department_name: Marketing Enter value for id: 37 1 row created.

SQL> START p11q1g SQL> SET ECHO OFF Enter value for department_name: Sales Enter value for id: 54 1 row created.

SQL> START p11q1g SQL> SET ECHO OFF Enter value for department_name: Personnel Enter value for id: 75 1 row created.

Practice Solutions

A73

Practice 11 Solutions
1.continued h.

continued

Execute the p11q1d.sql script to add the following rows to the EMPLOYEE table: Albert Jones in department number 54, and employee number 201; Harry Chin in department 75 and employee number 202; Rey Guiliani in department 37 and employee number 203. SQL> START p11q1d SQL> SET ECHO OFF Enter value for first_name: Albert Enter value for last_name: Jones Enter value for department_number: 54 Enter value for employee_number: 201 1 row created.

SQL> START p11q1d SQL> SET ECHO OFF Enter value for first_name: Harry Enter value for last_name: Chin Enter value for department_number: 75 Enter value for employee_number: 202 1 row created.

SQL> START p11q1d SQL> SET ECHO OFF Enter value for first_name: Rey Enter value for last_name: Guiliani Enter value for department_number: 37 Enter value for employee_number: 203 1 row created.

A74

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11 Solutions
1.continued i.

continued

Confirm your additions to the tables. SQL> SELECT 2 FROM * department;

ID ---10 37 54 75

NAME ------------------------Finance Marketing Sales Personnel

SQL> SELECT 2 FROM

* employee;

ID ---200 201 202 203


j.

LAST_NAME ---------Smith Jones Chin Guiliani

FIRST_NAME DEPT_ID ---------- -------Donna 10 Albert 54 Harry 75 Rey 37

Make the data additions permanent. SQL> COMMIT; Commit complete.

Practice Solutions

A75

Practice 11 Solutions
2.

continued

Update and delete data in the DEPARTMENT and EMPLOYEE tables.


a.

Change the name of the Personnel department to Human Resources. SQL> UPDATE 2 SET 3 WHERE department name = Human Resources id = 75;

1 row updated.
b.

Change the last name of employee 202 to Korsgaard. SQL> UPDATE 2 SET 3 WHERE employee last_name = Korsgaard id = 202;

1 row updated.
c.

Verify your changes to the tables. SQL> SELECT 2 FROM 3 WHERE * department name = Human Resources;

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

SQL> SELECT 2 FROM 3 WHERE

* employee id = 202;

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

A76

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11 Solutions
2.continued d.

continued

Attempt to delete department 54. What was the result and why? SQL> DELETE FROM department 2 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 to department number 54 in the EMPLOYEE table. e. Delete Albert Jones from the EMPLOYEE table.
"

SQL> SELECT 2 FROM 3 WHERE

* employee last_name = Jones;

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

SQL> DELETE FROM 2 WHERE 1 row deleted.

employee id = 201;

Practice Solutions

A77

Practice 11 Solutions
2.continued f.

continued

Attempt to delete department 54 from the DEPARTMENT table again. What was the result and why? SQL> DELETE FROM 2 WHERE 1 row deleted.
"

department id = 54;

The deletion is successful now because the foreign key reference to department number 54 was removed when the record for Albert Jones was deleted.

g.

Verify the changes to your tables. SQL> SELECT 2 FROM * department;

ID ---10 37 75

NAME ------------------------Finance Marketing Human Resources

SQL> SELECT 2 FROM

* employee;

ID ---200 202 203

LAST_NAME ---------Smith Korsgaard Guiliani

FIRST_NAME DEPT_ID ---------- -------Donna 10 Harry 75 Rey 37

A78

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11 Solutions
2.continued h.

continued

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 department number 54. SQL> start p11q1g SQL> SET ECHO OFF Enter value for department_name: Sales Enter value for id: 54 1 row created.

b.

Verify your addition. SQL> SELECT 2 FROM 3 WHERE * department id = 54;

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


c.

Mark a transaction processing savepoint. SQL> SAVEPOINT sales;

Practice Solutions

A79

Practice 11 Solutions
3.continued d.

continued

Empty the entire EMPLOYEE table. SQL> DELETE FROM 3 rows deleted. employee;

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 most recent INSERT operation. SQL> ROLLBACK TO sales; Rollback complete.

g.

Verify that the new row in the DEPARTMENT table is still intact. Verify that the EMPLOYEE table has all three rows. SQL> SELECT 2 FROM * department;

ID ---10 37 54 75

NAME ------------------------Finance Marketing Sales Human Resources

A80

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 11 Solutions
3g.continued

continued

SQL> SELECT 2 FROM

* employee;

ID ---200 202 203


h.

LAST_NAME ---------Smith Korsgaard Guiliani

FIRST_NAME DEPT_ID ---------- -------Donna 10 Harry 75 Rey 37

Make the data addition permanent. SQL> COMMIT; Commit complete.

Practice Solutions

A81

Practice 12 Solutions
1.

Create a WORKER table, which copies the data from the EMPLOYEE table. Describe the table to confirm its structure. SQL> CREATE TABLE worker 2 AS (SELECT * 3 FROM employee); Table created.

SQL> DESCRIBE worker Name -------------------------ID LAST_NAME FIRST_NAME DEPT_ID


2.

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

View the constraints for this new table. Save this command to a script named p12q2.sql. Note the types and names of the constraints. SQL> SELECT 2 3 FROM 4 WHERE constraint_name, constraint_type, search_condition, r_constraint_name user_constraints table_name = WORKER;

CONSTRAINT_NAME --------------SYS_C00108545 SYS_C00108546 SQL> SAVE p12q2

C C C

SEARCH_CONDITION R_CONSTRAI --------------------- ---------LAST_NAME IS NOT NULL DEPT_ID IS NOT NULL

Created file p12q2


"

Your constraint names may be different from those listed here because they are system generated.

A82

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 12 Solutions
3.

continued

Compare these constraints to those in the EMPLOYEE table. Note the types and names of the constraints. SQL> SELECT 2 3 FROM 4 WHERE constraint_name, constraint_type, search_condition, r_constraint_name user_constraints table_name = EMPLOYEE;

CONSTRAINT_NAME --------------EMP_LAST_NN EMP_DEPT_ID_NN EMP_ID_PK EMP_DEPT_ID_FK


4.

C C C P R

SEARCH_CONDITION R_CONSTRAI --------------------- ---------LAST_NAME IS NOT NULL DEPT_ID IS NOT NULL DEPT_ID_PK

Add a table level PRIMARY KEY constraint to the WORKER table using the ID column. The constraint should be immediately enabled. SQL> ALTER TABLE 2 ADD CONSTRAINT Table altered. worker worker_id_pk PRIMARY KEY(id);

5.

Add a foreign key reference from the DEPARTMENT table to the DEPTARTMENT_ID column in the WORKER table. Confirm that the constraints were added by re-executing p12q2.sql. SQL> ALTER TABLE 2 ADD CONSTRAINT 3 4 Table altered. worker worker_dept_id_fk FOREIGN KEY(dept_id) REFERENCES department(id);

Practice Solutions

A83

Practice 12 Solutions
5.continued

continued

SQL> START p12q2

CONSTRAINT_NAME --------------SYS_C00108545 SYS_C00108546 WORKER_ID_PK P WORKER_DEPT_ID_FK


6.

C C C R

SEARCH_CONDITION R_CONSTRAI --------------------- ---------LAST_NAME IS NOT NULL DEPT_ID IS NOT NULL DEPT_ID_PK

Display the object names and types from the USER_OBJECTS data dictionary view. You may want to format the columns for readability. Notice that the new table and a new index were created. SQL> COLUMN object_name FORMAT A30 SQL> SELECT object_name, object_type 2 FROM user_objects 3 ORDER BY object_name;

OBJECT_NAME -----------------------------DEPARTMENT DEPT_ID_PK EMPLOYEE EMP_ID_PK S_CUSTOMER S_CUSTOMER_ID S_CUSTOMER_ID_PK S_DEPT S_DEPT_ID

OBJECT_TYPE ------------TABLE INDEX TABLE INDEX TABLE SEQUENCE INDEX TABLE SEQUENCE

A84

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 12 Solutions
6.continued

continued

S_DEPT_ID_PK S_DEPT_NAME_REGION_ID_UK S_EMP S_EMP_ID S_EMP_ID_PK S_EMP_USERID_UK S_IMAGE S_IMAGE_ID S_IMAGE_ID_PK S_INVENTORY S_INVENTORY_PRODID_WARID_PK S_ITEM S_ITEM_ORDID_ITEMID_PK S_ITEM_ORDID_PRODID_UK S_LONGTEXT S_LONGTEXT_ID S_LONGTEXT_ID_PK S_ORD S_ORD_ID S_ORD_ID_PK S_PRODUCT S_PRODUCT_ID S_PRODUCT_ID_PK S_PRODUCT_NAME_UK S_REGION S_REGION_ID S_REGION_ID_PK S_REGION_NAME_UK S_TITLE S_TITLE_TITLE_PK S_WAREHOUSE S_WAREHOUSE_ID S_WAREHOUSE_ID_PK WORKER WORKER_ID_PK 44 rows selected.

INDEX INDEX TABLE SEQUENCE INDEX INDEX TABLE SEQUENCE INDEX TABLE INDEX TABLE INDEX INDEX TABLE SEQUENCE INDEX TABLE SEQUENCE INDEX TABLE SEQUENCE INDEX INDEX TABLE SEQUENCE INDEX INDEX TABLE INDEX TABLE SEQUENCE INDEX TABLE INDEX

Practice Solutions

A85

Practice 12 Solutions
7.

continued

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 2 ADD Table altered. worker (title VARCHAR2(30));

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

A86

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 12 Solutions
9.

continued

Add a comment to the WORKER and DEPARTMENT table definitions describing the tables. Confirm your additions in the data dictionary. TABLE_NAME --------------DEPARTMENT WORKER COMMENTS -----------------------------Departmental Listing Employee Information

SQL> COMMENT ON TABLE department 2 IS Departmental Listings; Comment created.

SQL> COMMENT ON TABLE worker 2 IS Employee Information; Comment created.

SQL> SELECT 2 FROM 3 WHERE 4

table_name, comments user_tab_comments table_name IN (WORKER,DEPARTMENT);

TABLE_NAME --------------DEPARTMENT WORKER

COMMENTS -----------------------------Departmental Listing Employee Information

Practice Solutions

A87

Practice 13 Solutions
1.

Create a sequence to be used with the DEPARTMENT tables primary key column. The sequence should start at 76 and have a maximum value of 80. Be sure that it increments by one. Name the sequence DEPT_ID_SEQ. SQL> CREATE SEQUENCE dept_id_seq 2 START WITH 76 3 MAXVALUE 80 4 NOCACHE 5 NOCYCLE; Sequence created.

2.

Create another sequence. This sequence will be used with the WORKER tables primary key column. Start this sequence at 204, and set the maximum value to be 9999999. Be sure that it increments by one. Allow the sequence to cache 5 numbers. Name the sequence WORKER_ID_SEQ. SQL> CREATE SEQUENCE 2 START WITH 3 MAXVALUE 4 CACHE 5 NOCYCLE; Sequence created. worker_id_seq 204 9999999 5

A88

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 13 Solutions
3.

continued

Write a script to display the following information about your sequences: sequence name, cache size, maximum value, increment size, and last number generated. Name the script p13q3.sql. SET ECHO OFF COLUMN sequence_name FORMAT A15 SELECT sequence_name, cache_size, max_value, increment_by, last_number FROM user_sequences WHERE 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 76 WORKER_ID_SEQ 5 9999999 1 204

4.

Write an interactive script to insert a row into the DEPARTMENT table. Name your 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 your additions. SET ECHO OFF ACCEPT name PROMPT Enter the department name: INSERT INTO department (id, name) VALUES (dept_id_seq.NEXTVAL, &name) / SET ECHO ON

Practice Solutions

A89

Practice 13 Solutions
4.continued

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 10 37 76 75 54 77

NAME ------------------------Finance Marketing Education Human Resources Sales Administration

A90

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 13 Solutions
5.

continued

Write a script to insert two rows into the WORKER table. Name your script p13q5.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 the table. The other employee is Anna Seigher who is the Vice President in the Finance department. SET ECHO OFF INSERT 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 OFF Enter value for first_name: Tomas Enter value for last_name: Lira Enter value for department_number: 77 Enter value for title: President 1 row created.

SQL> START p13q5 SQL> SET ECHO OFF Enter value for first_name: Anna Enter value for last_name: Seigler Enter value for department_number: 10 Enter value for title: Vice President 1 row created.

Practice Solutions

A91

Practice 13 Solutions
6.

continued

Confirm your additions to the DEPARTMENT table and WORKER table. Note the highest primary key values for each table. SQL> SELECT 2 FROM * department;

ID ---10 37 76 75 54 77

NAME ------------------------Finance Marketing Education Human Resources Sales Administration

SQL> SELECT 2 FROM

* worker;

ID ---200 204 202 203 205

LAST_NAME ---------Smith Lira Korsgaard Guiliani Seigler

FIRST_NAME DEPT_ID TITLE ---------- -------- --------------Donna 10 Tomas 77 President Harry 75 Rey 37 Anna 10 Vice President

A92

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 13 Solutions
7.

continued

Display information about your sequences by executing the p13q3.sql script. Notice that the WORKER_ID_SEQ last number does not match the highest primary 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 78 WORKER_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 OFF Enter the department name: Accounting 1 row created.

SQL> START p13q4 SQL> SET ECHO OFF Enter the department name: Warehouse 1 row created.

SQL> START p13q4 SQL> SET ECHO OFF Enter the department name: Operations 1 row created.

Practice Solutions

A93

Practice 13 Solutions
8.continued

continued

SQL> START p13q4 SQL> SET ECHO OFF Enter the department name: Research VALUES (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 change to 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 80 WORKER_ID_SEQ 5 9999999 1 209

A94

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 13 Solutions
10.

continued

Add the Research department by using your script named p13q4.sql. Make this addition permanent. SQL> START p13q4 SQL> SET ECHO OFF Enter 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 ---10 37 76 75 54 77 78 79 80 81

NAME ------------------------Finance Marketing Education Human Resources Sales Administration Accounting Warehouse Operations Research

10 rows selected.

Practice Solutions

A95

Practice 13 Solutions
11.continued

continued

SQL> SELECT 2 FROM

* worker;

ID ---200 204 202 203 205

LAST_NAME ---------Smith Lira Korsgaard Guiliani Seigler

FIRST_NAME DEPT_ID TITLE ---------- -------- --------------Donna 10 Tomas 77 President Harry 75 Rey 37 Anna 10 Vice President

A96

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 14 Solutions
1.

Create a view called EMP_VU based on the employee number, last name, and department number from the WORKER table. Change the heading for the last name to EMPLOYEE. SQL> CREATE VIEW EMP_VU AS 2 SELECT id, last_name employee, 3 dept_id 5 FROM worker; View created.
a.

Display the content of the EMP_VU view. SQL> SELECT 2 FROM * emp_vu;

ID --------200 202 203 204 205

EMPLOYEE DEPARTMENT_ID ------------------------- ------------Smith 10 Korsgaard 75 Guiliani 37 Lira 77 Seigler 10

Practice Solutions

A97

Practice 14 Solutions
1.continued b.

continued

Write a script to display the definition of a view. Pass the name of the view to the script. Save the script as p14q1.sql. Execute the script to view the definition of the EMP_VU view. SET ECHO OFF SET VERIFY OFF SET LONG 200 COLUMN view_name FORMAT A15 COLUMN text FORMAT A50 SELECT * FROM user_views WHERE view_name = UPPER(&view) / COLUMN text CLEAR COLUMN view_name CLEAR SET LONG 80 SET ECHO ON

SQL> START p14q1 SQL> SET ECHO OFF Enter 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 2 SET 3 WHERE emp_vu dept_id = 37 employee = Smith;

1 row updated.

A98

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 14 Solutions
1.continued d.

continued

Confirm that Smith is now assigned to department 37. SQL> SELECT 2 FROM * emp_vu;

ID --------200 202 203 204 205


2.

EMPLOYEE DEPARTMENT_ID ------------------------- ------------Smith 37 Korsgaard 75 Guiliani 37 Lira 77 Seigler 10

Create a view called MNS_VU that contains the employee number, full name, and department name for all employees in the Marketing and Sales departments in the WORKER and DEPARTMENT tables. Save the command in a script named p14q2.sql. SQL> 2 3 4 5 6 CREATE OR REPLACE VIEW mns_vu AS SELECT w.id, w.first_name|| ||w.last_name full_name, d.name FROM worker w, department d WHERE w.dept_id = d.id AND d.id IN (37, 54);

View created.

Practice Solutions

A99

Practice 14 Solutions
2.continued a.

continued

Display the structure and contents of the MNP_VU view. SQL> DESCRIBE mns_vu Name Null? ----------------------------- -------ID NOT NULL FULL_NAME NAME Type ---NUMBER(7) VARCHAR2(51) VARCHAR2(25)

SQL> SELECT 2 FROM

* mns_vu;

ID --------200 203

FULL_NAME -----------------------Donna Smith Rey Guiliani

NAME ------------Marketing Marketing

b.

Display the definition of the MNS_VU view by executing the p14q1.sql script.
SQL> START p14q1 SQL> SET ECHO OFF Enter value for view: mns_vu VIEW_NAME TEXT_LENGTH TEXT -------------- ----------- -----------------------------MNS_VU 140 SELECT w.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)

A100

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 14 Solutions
2.continued c.

continued

Display the department name and number of employees in each department. SQL> SELECT name, COUNT(*) 2 FROM mns_vu 3 GROUP BY name;

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


3.

Modify EMP_VU view to contain only those employees in department 37. Add a check constraint so that the department number cannot be modified. SQL> 2 3 4 5 6 CREATE OR REPLACE VIEW EMP_VU AS SELECT id, last_name employee, dept_id FROM worker WHERE dept_id = 37 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 --------200 203

EMPLOYEE DEPT_ID ------------------------- ------------Smith 37 Guiliani 37

Practice Solutions

A101

Practice 14 Solutions
3.continued b.

continued

Change the department number for Smith back to 54 through the EMP_VU view. Was your operation successful? Why or why not? SQL> UPDATE 2 SET 3 WHERE emp_vu dept_id = 54 employee = Smith;

WHERE employee = Smith * ERROR at line 3: ORA-01402: view WITH CHECK OPTION where-clause violation The operation was unsuccessful because the CHECK OPTION constraint does not allow the department number to be changed in the view. 4. Modify the MNS_VU so that the rows can only be seen between 1:00 P.M. and 4:00 P.M. You can edit the script named p14q2.sql. Execute the script. Display the contents of the view.
"

CREATE OR REPLACE VIEW MNS_VU AS SELECT w.id, w.first_name|| ||w.last_name full_name, d.name FROM worker w, department d WHERE w.dept_id = d.id AND d.id IN (37, 54) AND TO_CHAR(SYSDATE,hh24mi) BETWEEN 1300 and 1600;

SQL> START p14q2 View created.

A102

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 14 Solutions
4.continued
"

continued

If your server s time is between the time range specified, you will see the following result. Otherwise, the SELECT statement yields no rows. * mns_vu;

SQL> SELECT 2 FROM

ID --------200 203
5.

FULL_NAME -----------------------Donna Smith Rey Guiliani

NAME --------------Marketing Marketing

Remove all views from the data dictionary. Confirm that no views exist in the data dictionary. SQL> SELECT 2 FROM view_name user_views;

VIEW_NAME -----------------------------EMP_VU MNS_VU

SQL> DROP VIEW View dropped.

emp_vu;

SQL> DROP VIEW View dropped.

mns_vu;

Practice Solutions

A103

Practice 14 Solutions
5.continued

continued

SQL> SELECT 2 FROM

view_name user_views;

no rows selected

A104

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 15 Solutions
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. * s_emp last_name = Biri;

SQL> SELECT 2 FROM 3 WHERE


b.

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


"

No because the WHERE clause does not specify a column that has an index on it. id, customer_id, total s_ord date_ordered = 31-AUG-92;

SQL> SELECT 2 FROM 3 WHERE


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. e.last_name, d.name s_emp e, s_dept d e.dept_id = d.id;

SQL> SELECT 2 FROM 3 WHERE

Practice Solutions

A105

Practice 15 Solutions
2.

continued

Create a non-unique index on the foreign key column in the WORKER table. SQL> CREATE INDEX worker_dept_id_idx 2 ON worker(dept_id); Index created.

3.

Since users will frequently query on the employee last name, create a non-unique index on that column in the WORKER table. SQL> CREATE INDEX worker_last_name_idx 2 ON worker(last_name); Index created.

4.

Display the indexes and uniqueness that exist in the data dictionary for the WORKER and DEPARTMENT tables. Save the command into a script named p15q4.sql. SET ECHO OFF COLUMN index_name FORMAT A20 COLUMN table_name FORMAT A15 SELECT index_name, table_name, uniqueness FROM user_indexes WHERE table_name IN (WORKER,DEPARTMENT) / COLUMN index_name CLEAR COLUMN table_name CLEAR SET ECHO ON

A106

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 15 Solutions
4.continued

continued

SQL> START p15q4 SET ECHO OFF INDEX_NAME -------------------DEPT_ID_PK WORKER_DEPT_ID_IDX WORKER_ID_PK WORKER_LAST_NAME_IDX
5.

TABLE_NAME --------------DEPARTMENT WORKER WORKER WORKER

UNIQUENES --------UNIQUE NONUNIQUE UNIQUE NONUNIQUE

Remove the primary key constraint on the WORKER table. SQL> ALTER TABLE worker 2 DROP CONSTRAINT worker_id_pk; Table altered.

6.

Re-display the indexes and uniqueness that exist in the data dictionary for the WORKER and DEPARTMENT tables by executing the p15q4.sql script. What changes do you observe and why?
"

The WORKER_ID_PK index is no longer in the list because when the primary key constraint on the WORKER table was dropped, the index was no longer required and therefore automatically removed. SQL> START p15q4 SET ECHO OFF INDEX_NAME -------------------DEPT_ID_PK WORKER_DEPT_ID_IDX WORKER_LAST_NAME_IDX TABLE_NAME --------------DEPARTMENT WORKER WORKER UNIQUENES --------UNIQUE NONUNIQUE NONUNIQUE

Practice Solutions

A107

Practice 15 Solutions
7.

continued

Re-create the primary key constraint on the WORKER table. Confirm the constraint in the data dictionary by executing pl2q2.sql. Confirm the unique index in the data dictionary by executing pl5q4. SQL> ALTER TABLE worker 2 ADD CONSTRAINT worker_id_pk PRIMARY KEY(id); Table altered.

SQL> START pl2q2 CONSTRAINT_NAME ------------------SYS_C00108623 SYS_C00108624 WORKER_ID_PK WORKER_DEPT_ID_FK C C C P R

SQL> START p15q4 SET ECHO OFF INDEX_NAME -------------------DEPT_ID_PK WORKER_DEPT_ID_IDX WORKER_ID_PK WORKER_LAST_NAME_IDX
8.

TABLE_NAME --------------DEPARTMENT WORKER WORKER WORKER

UNIQUENES --------UNIQUE NONUNIQUE UNIQUE NONUNIQUE

Remove the index on the employee last name from the WORKER table. SQL> DROP INDEX worker_last_name_idx; Index dropped.

A108

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 16 Solutions
1.

What privilege should a user be given to log in to the Oracle7 Server? Is this privilege 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 WITH GRANT OPTION.

4.

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

Create a role containing the system privileges and allocate the role to the users. 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 you query access to their S_REGION table.
"

Team 2 executes the GRANT command. SQL> GRANT 2 ON 3 TO select s_region user1;

Grant succeeded.
"

Team 1 executes the GRANT command. SQL> GRANT 2 ON 3 TO select s_region user2;

Grant succeeded.
"

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

Practice Solutions

A109

Practice 16 Solutions
7.

continued

Query all the rows in your S_REGION table. SQL> SELECT 2 FROM * s_region;

ID ------1 2 3 4 5
8.

NAME --------------North America South America Africa / Middle East Asia Europe

Add a new row to your S_REGION table. Team 1 should add Central America as region number 6. Team 2 should add Micronesia as region number 7. Make the changes 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.

A110

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 16 Solutions
9.

continued

Query the other teams S_REGION table.


"

Team 1 executes the query. SQL> SELECT 2 FROM * user2.s_region;

ID ------1 2 3 4 5 7

NAME --------------North America South America Africa / Middle East Asia Europe Micronesia

6 rows selected.
"

Team 2 executes the query. SQL> SELECT 2 FROM * user1.s_region;

ID ------1 2 3 4 5 6

NAME --------------North America South America Africa / Middle East Asia Europe Centeral America

6 rows selected.

Practice Solutions

A111

Practice 16 Solutions
10.

continued

Create a synonym for the other teams S_REGION table.


"

Team 1 creates a synonym named team2. SQL> CREATE SYNONYM 2 FOR Synonynm created. team2 user2.s_region;

"

Team 2 creates a synonym named team1. SQL> CREATE SYNONYM 2 FOR Synonynm created. team1 user1.s_region;

11.

Display the other teams S_REGION table contents by using your synonym.
"

Team 1 executes the query. SQL> SELECT 2 FROM * team2;

ID ------1 2 3 4 5 7

NAME --------------North America South America Africa / Middle East Asia Europe Micronesia

6 rows selected.

A112

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 16 Solutions
11.continued
"

continued

Team 2 executes the query. SQL> SELECT 2 FROM * team1;

ID ------1 2 3 4 5 6

NAME --------------North America South America Africa / Middle East Asia Europe Central America

6 rows selected.
12.

Confirm the privileges in effect for your teams 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

Practice Solutions

A113

Practice 16 Solutions
12.continued
"

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 2 ON 3 FROM select s_region user2;

Revoke succeeded.
"

Team 2 revokes the privilege. SQL> REVOKE 2 ON 3 FROM select s_region user1;

Revoke succeeded.

A114

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 16 Solutions
14.

continued

Attempt to SELECT from the other teams 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 Synonym dropped. team2;

"

Team 2 drops the synonym. SQL> DROP SYNONYM Synonym dropped. team1;

Practice Solutions

A115

Practice 17 Solutions
1.

Create the tables based on the entity relationship diagram on the previous page and the table instance charts below. Choose the appropriate datatypes and be sure to add the integrity constraints.
a.

Table name: MEMBER


MEMBER_ ID LAST_ FIRST_ NAME NAME ADDRESS CITY PHONE JOIN_DATE

Column Name Key Type Null/ Unique Default Value

PK NN, U NN NN System date char 25 char 25 char 100 char 30 char 15 date

Datatype number Length 10

SQL> CREATE TABLE 2 (member_id 3 CONSTRAINT 4 last_name 5 CONSTRAINT 6 first_name 7 address 8 city 9 phone 10 join_date 11 CONSTRAINT Table created.

MEMBER NUMBER (10) member_id_pk PRIMARY KEY, VARCHAR2(25) member_last_nn NOT NULL, VARCHAR2(25), VARCHAR2(100), VARCHAR2(30), VARCHAR2(15), DATE DEFAULT SYSDATE join_date_nn NOT NULL);

A116

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
1.continued b.

continued

Table name: TITLE


TITLE_ ID RELEASE_ DATE

Column Name Key Type Null/ Unique Check

TITLE DESCRIPTION RATING CATEGORY

PK NN, U NN NN G, PG, R, NC17, NR DRAMA, COMEDY, ACTION, CHILD, SCIFI, DOCUMENTA RY DRAMA char 400 char 4 char 20 date

Default Value Datatype number char Length 10 60

Practice Solutions

A117

Practice 17 Solutions
1b.continued

continued

SQL> CREATE TABLE title 2 (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 CHECK 10 (rating IN (G,PG,R,NC17,NR)), 11 category VARCHAR2(20) DEFAULT DRAMA 12 CONSTRAINT title_categ_ck CHECK 13 (category IN (DRAMA, COMEDY, ACTION, 14 CHILD, SCIFI, DOCUMENTARY)), 15 release_date DATE); Table created.

A118

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
1.continued c.

continued

Table name: TITLE_COPY


COPY_ID TITLE_ID STATUS

Column Name Key Type Null/ Unique Check FK Ref Table FK Ref Col Datatype Length

PK NN, U

PK, FK NN, U NN AVAILABLE, DESTROYED, RENTED, RESERVED title title_id

number 10

number 10

char 15

SQL> CREATE TABLE title_copy 2 (copy_id NUMBER(10), 3 title_id NUMBER(10) 4 CONSTRAINT copy_title_id_fk REFERENCES 5 title(title_id), 6 status VARCHAR2(15) 7 CONSTRAINT copy_status_nn NOT NULL 8 CONSTRAINT copy_status_ck CHECK 9 (status IN (AVAILABLE, DESTROYED, 10 RENTED, RESERVED)), 11 CONSTRAINT copy_title_id_pk 12 PRIMARY KEY(copy_id, title_id)); Table created.

Practice Solutions

A119

Practice 17 Solutions
1.continued d.

continued

Table name: RENTAL


BOOK_ DATE MEMBER_ ID COPY_ID ACT_RET_ DATE EXP_RET_ DATE TITLE_ID

Column Name Null/ Unique Default Value FK Ref Table FK Ref Col

Key Type PK NN,U System date

FK NN

PK, FK NN,U 2 days after book date

PK, FK NN,U

member member_id number 10

title_copy copy_id number 10 date date

title_copy title_id number 10

Datatype date Length

SQL> CREATE TABLE rental 2 (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 KEY 14 (book_date, copy_id, title_id)); Table created.

A120

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
1.continued e.

continued

Table name: RESERVATION


RES_DATE MEMBER_ID TITLE_ID

Column Name Key Type Null/ Unique FK Ref Table FK Ref Col Datatype Length

PK NN,U

PK, FK NN,U member member_id

PK, FK NN,U title title_id number 10

date

number 10

SQL> 2 3 4 5 6 7 8 9 10

CREATE TABLE reservation (res_date DATE, member_id NUMBER(10) CONSTRAINT res_member_id_fk REFERENCES member (member_id), title_id NUMBER(10) CONSTRAINT res_title_id_fk REFERENCES title (title_id), CONSTRAINT res_id_pk PRIMARY KEY (res_date, member_id, title_id));

Table created.

Practice Solutions

A121

Practice 17 Solutions
2.

continued

Verify that the tables and constraints were created properly by checking the data dictionary. SQL> SELECT 2 FROM 3 WHERE 4 object_name user_objects object_name IN (MEMBER,TITLE, TITLE_COPY,RENTAL,RESERVATION);

OBJECT_NAME ------------------RESERVATION RENTAL TITLE_COPY TITLE MEMBER

SQL> SELECT 2 3 4 FROM 5 WHERE 6

constraint_name, constraint_type, table_name, search_condition, r_constraint_name user_constraints table_name IN (MEMBER,TITLE, TITLE_COPY,RENTAL,RESERVATION);

A122

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
2.continued CONSTRAINT_NAME C R_CONSTRAINT_NAME -------------------- ----------------- MEMBER_LAST_NN C JOIN_DATE_NN C MEMBER_ID_PK P RENTAL_ID_PK P RENTAL_MBR_ID_FK R MEMBER_ID_PK RENTAL_COPY_TITLE_ID R COPY_TITLE_ID_PK_FK RES_MEMBER_ID_FK R MEMBER_ID_PK RES_TITLE_ID_FK R TITLE_ID_PK RES_ID_PK P TITLE_NN C TITLE_DESC_NN C TITLE_ID_PK TITLE_RATING_NN TITLE_RATING_CK TITLE_CATEG_NN TITLE_CATEG_CK P C C C C TABLE_NAME SEARCH_CONDITION

continued

--------------- --------------------- MEMBER MEMBER MEMBER RENTAL RENTAL RENTAL RESERVATION RESERVATION RESERVATION TITLE TITLE TITLE TITLE TITLE TITLE TITLE LAST_NAME IS NOT NULL JOIN_DATE IS NOT NULL

TITLE IS NOT NULL DESCRIPTION IS NOT NU LL RATING IS NOT NULL rating IN (G,PG, R,NC17,NR) RATING IS NOT NULL category IN (DRAMA, COMEDY,ACTION, CHILD,SCIFI, DOCUMENTARY) STATUS IS NOT NULL status IN (AVAILABLE, DESTROYED,RENTED, RESERVED)

COPY_STATUS_NN COPY_STATUS_CK

C C

TITLE_COPY TITLE_COPY

COPY_TITLE_ID_PK COPY_TITLE_ID_FK 16 rows selected.

P R

TITLE_COPY TITLE_COPY

Practice Solutions

A123

Practice 17 Solutions
3.

continued

Create sequences to uniquely identify each row in the MEMBER table and the TITLE table.
a.

Member number for the MEMBER table, start with 101, do not allow caching of the values. SQL> CREATE SEQUENCE member_id_seq 2 START WITH 101 3 NOCACHE; Sequence created.

b.

Title number for the TITLE table, start with 92, no caching. SQL> CREATE SEQUENCE title_id_seq 2 START WITH 92 3 NOCACHE; Sequence created.

c.

Verify the existence of the sequences in the data dictionary. SQL> SELECT 2 3 FROM 4 WHERE 5 sequence_name, increment_by, last_number user_sequences sequence_name IN (MEMBER_ID_SEQ, TITLE_ID_SEQ);

SEQUENCE_NAME INCREMENT_BY LAST_NUMBER --------------- ------------ ----------MEMBER_ID_SEQ 1 101 TITLE_ID_SEQ 1 92

A124

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4.

continued

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 movie information. Save the script as p17q4a.sql. Use the sequence to uniquely identify each title. Remember that single quotation marks in a character field must be specially handled. Verify your additions. Description Rating Category CHILD Release date 05-OCT-95

Title Willie and Christmas Too Alien Again

All of Willies friends made a G Christmas list for Santa, but Willie has yet to add his own wish list. Yet another installment of science fiction history. Can the heroine save the planet from the alien life form? A meteor crashes near a small American town and unleashes carnivorous goo in this classic. With a little luck and a lot of ingenuity, a teenager skips school for a day in New York. A six-year-old has doubts about Santa Claus. But she discovers that miracles really do exist. After discovering a cache of drugs, a young couple find themselves pitted against a vicious gang. R

SCIFI

19-MAY-95

The Glob

NR

SCIFI

12-AUG-95

My Day Off

PG

COMEDY

12-JUL-95

Miracles on Ice

PG

DRAMA

12-SEP-95

Soda Gang

NR

ACTION

01-JUN-95

Practice Solutions

A125

Practice 17 Solutions
4a.continued

continued

SET ECHO OFF INSERT INTO title (title_id, title, description, rating, category, release_date) VALUES (title_id_seq.nextval, Willie and Christmas Too, All of Willies 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 fiction history. Can the heroine save the planet from the alien 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 unleashes carnivorous 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) /

A126

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4a.continued

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 OFF 1 row created. 1 row created. 1 row created. 1 row created. 1 row created. 1 row created. Commit complete.

Practice Solutions

A127

Practice 17 Solutions
4a.continued

continued

SQL> SELECT * 2 FROM title 3 ORDER BY title_id;

TITLE_ID TITLE ---------- ------------------------DESCRIPTION ------------------------------------------------RATI CATEGORY RELEASE_D ---- -------------------- --------92 Willie and Christmas Too All of Willies friends made a Christmas list for Santa, but Willie has yet to create his own wish list. G CHILD 05-OCT-95 93 Alien Again Another installment of science fiction history. Can the heroine save the planet from the alien life form? R SCIFI 19-MAY-95 94 The Glob A meteor crashes near a small American town and unleashes carnivorous goo in this classic. NR SCIFI 12-AUG-95 95 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

A128

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4a.continued

continued

TITLE_ID TITLE ---------- ------------------------DESCRIPTION ------------------------------------------------RATI CATEGORY RELEASE_D ---- -------------------- --------96 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 97 Soda Gang After discovering a cached of drugs, a young couple find themselves pitted against a vicious gang. NR ACTION 01-JUN-95 6 rows selected.

Practice Solutions

A129

Practice 17 Solutions
4.continued b.

continued

Add data to the MEMBER table. Write a script named p17q4b.sql to prompt users for the information. Execute the script. Be sure to use the sequence to add the member numbers.

First name Carmen LaDoris Midori Mark Audry Molly

Last name Velasquez Ngao Nagayama

Address 283 King Street 5 Modrany 68 Via Centrale

City Seattle Bratislava Sao Paolo

Phone 206-899-6666 586-355-8882 254-852-5764 63-559-7777 41-559-87 418-542-9988

Join date 08-MAR-90 08-MAR-90 17-JUN-91 07-APR-90 18-JAN-91 18-JAN-91

Quick-To-See 6921 King Lagos Way Ropeburn Urguhart 86 Chu Street 3035 Laurier Blvd Hong Kong Quebec

"

Script p17q4b.sql contents.

SET ECHO OFF INSERT 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

A130

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4b.continued

continued

SQL> START p17q4b SET ECHO OFF Enter value for first_name: Carmen Enter value for last_name: Velasquez Enter value for address: 283 King Street Enter value for city: Seattle Enter value for phone: 206-899-6666 Enter value for join_date: 08-MAR-90 1 row created. Commit complete.

SQL> START p17q4b SET ECHO OFF Enter value for first_name: LaDoris Enter value for last_name: Ngao Enter value for address: 5 Modrany Enter value for city: Bratislava Enter value for phone: 586-355-8882 Enter value for join_date: 08-MAR-90 1 row created. Commit complete.

SQL> START p17q4b SET ECHO OFF Enter value for first_name: Midori Enter value for last_name: Nagayama Enter value for address: 68 Via Centrale Enter value for city: Sao Paolo Enter value for phone: 254-852-5764 Enter value for join_date: 17-JUN-91 1 row created. Commit complete.

Practice Solutions

A131

Practice 17 Solutions
4b.continued

continued

SQL> START p17q4b SET ECHO OFF Enter value for first_name: Mark Enter value for last_name: Quick-To-See Enter value for address: 6921 King Way Enter value for city: Lagos Enter value for phone: 63-559-7777 Enter value for join_date: 07-APR-90 1 row created. Commit complete.

SQL> START p17q4b SET ECHO OFF Enter value for first_name: Audry Enter value for last_name: Ropeburn Enter value for address: 86 Chu Street Enter value for city: Hong Kong Enter value for phone: 41-559-87 Enter value for join_date: 18-JAN-91 1 row created. Commit complete.

SQL> START p17q4b SET ECHO OFF Enter value for first_name: Molly Enter value for last_name: Urguhart Enter value for address: 3035 Laurier Blvd Enter value for city: Quebec Enter value for phone: 418-542-9988 Enter value for join_date: 18-JAN-91 1 row created. Commit complete.

A132

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4b.continued
"

continued

Verify the additions. SQL> SELECT * 2 FROM member 3 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 586-355-8882 08-MAR-90 103 Nagayama Midori 68 Via Centrale 254-852-5764 17-JUN-91 104 Quick-To-S Mark ee 6921 King Way 63-559-777 07-APR-90

Bratislava

Sao Paolo

Lagos

Practice Solutions

A133

Practice 17 Solutions
4b.continued

continued

MEMBER_ID LAST_NAME FIRST_NAME ---------- ---------- ---------ADDRESS CITY ------------------------------ ---------PHONE JOIN_DATE --------------- --------105 Ropeburn Audry 86 Chu Street 41-559-87 04-MAR-90 106 Urguhart Molly 3035 Laurier Blvd. 418-542-9988 18-JAN-91

Hong Kong

Quebec

6 rows selected.

A134

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4.continued c.

continued

Add the following movie copies in the TITLE_COPY table: Copy number 1 1 2 1 1 2 3 Status Available Available Rented Available Available Available Rented Available Available

Title Willie and Christmas Too Alien Again The Glob My Day Off

Miracles on Ice Soda Gang

1 1

Practice Solutions

A135

Practice 17 Solutions
4c.continued
"

continued

Script p17q4c.sql contents.

SET ECHO OFF INSERT INTO title_copy (copy_id, VALUES (1, 92, AVAILABLE) / INSERT INTO title_copy (copy_id, VALUES (1, 93, AVAILABLE) / INSERT INTO title_copy (copy_id, VALUES (2, 93, RENTED) / INSERT INTO title_copy (copy_id, VALUES (1, 94, AVAILABLE) / INSERT INTO title_copy (copy_id, VALUES (1, 95, AVAILABLE) / INSERT INTO title_copy (copy_id, VALUES (2, 95, AVAILABLE) / INSERT INTO title_copy (copy_id, VALUES (3, 95, RENTED) / INSERT INTO title_copy (copy_id, VALUES (1, 96, AVAILABLE) / INSERT INTO title_copy (copy_id, VALUES (1, 97, AVAILABLE) / COMMIT / SET ECHO ON

title_id, status)

title_id, status)

title_id, status)

title_id, status)

title_id, status)

title_id, status)

title_id, status)

title_id, status)

title_id, status)

A136

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4c.continued

continued

SQL> START p17q4c SET ECHO OFF 1 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_copy 3 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.

Practice Solutions

A137

Practice 17 Solutions
4.continued d.

continued

Add the following rentals to the RENTAL table: Copy number Customer 101 101 102 106 Date rented Date return expected 3 days ago 1 day ago 2 days ago 4 days ago 1 day ago 1 day from now Today 2 days ago 2 days ago Date returned 2 days ago

Title

Willie and 1 Christmas Too Alien Again My Day Off Soda Gang 2 3 1

SQL> INSERT INTO rental (title_id, copy_id 2 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_id 2 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_id 2 member_id, book_date, exp_ret_date, 3 act_ret_date) 4 VALUES (95, 3, 102, SYSDATE-2, 5 SYSDATE, null); 1 row created.

A138

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
4d.continued

continued

SQL> INSERT INTO rental (title_id, copy_id 2 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 rental 3 ORDER BY title_id;

BOOK_DATE MEMBER_ID --------- ---------EXP_RET_D TITLE_ID --------- ---------07-FEB-96 101 09-FEB-96 92 09-FEB-96 11-FEB-96 08-FEB-96 10-FEB-96 06-FEB-96 08-FEB-96 101 93 102 95 106 97

COPY_ID ----------

ACT_RET_D ---------

08-FEB-96

08-FEB-96

Practice Solutions

A139

Practice 17 Solutions
5.

continued

Create a view named TITLE_AVAIL to show the movie titles and the availability of each copy and its expected return date if rented. Query all rows from the view. SQL> 2 3 4 5 6 7 CREATE VIEW title_avail AS SELECT t.title, c.copy_id, c.status, r.exp_ret_date FROM title t, title_copy c, rental r WHERE t.title_id = c.title_id AND c.copy_id = r.copy_id(+) AND c.title_id = r.title_id(+);

View created.

SQL> SELECT * 2 FROM title_avail 3 ORDER BY title, copy_id;

TITLE COPY_ID STATUS --------------- -------- ---------Alien Again 1 AVAILABLE Alien Again 2 RENTED Miracles on Ice 1 AVAILABLE My Day Off 1 AVAILABLE My Day Off 2 AVAILABLE My Day Off 3 RENTED Soda Gang 1 AVAILABLE The Glob 1 AVAILABLE Willie and 1 AVAILABLE Christmas Too

EXP_RET_D --------11-FEB-96

10-FEB-96 08-FEB-96 09-FEB-96

9 rows selected.

A140

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
6.

continued

Make changes to data in the tables.


a.

Add a new title. The movie is Interstellar Wars, which is rated PG, and classified 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 the evil Empire? Be sure to add a title copy record for two copies. SQL> 2 3 4 5 6 7 INSERT INTO title (title_id, title, description, rating, category, release_date) VALUES (title_id_seq.nextval, Interstellar Wars, Futuristic interstellar action movie. Can the rebels save the humans from the evil Empire?, PG, SCIFI, 07-JUL-77);

1 row created.
"

Obtain the title number for use in the TITLE_COPY table. SQL> SELECT 2 FROM 3 WHERE title_id, title title 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.

Practice Solutions

A141

Practice 17 Solutions
6a.continued

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 wants to rent Interstellar Wars. The other is for Mark Quick-To-See who wants to rent Soda Gang. SQL> 2 3 4 SELECT FROM WHERE IN member_id, first_name, last_name member last_name (Velasquez,Quick-To-See);

MEMBER_ID ---------101 104

FIRST_NAME ---------Carmen Mark

LAST_NAME -----------Velasquez Quick-To-See

SQL> 2 3 4

SELECT FROM WHERE IN

title_id, title title title (Interstellar Wars,Soda Gang);

TITLE_ID TITLE ---------- --------------97 Soda Gang 98 Interstellar Wars

A142

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
6b.continued

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 98 10-FEB-96 104 97

Practice Solutions

A143

Practice 17 Solutions
6.continued c.

continued

Customer Carmen Velasquez rents the movie Interstellar Wars, copy 1. Remove her reservation for the movie. Record the information about the rental. Allow the default value for the expected return date to be used. Verify the 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> 2 3 4 UPDATE title_copy SET status = RENTED WHERE title_id = 98 AND copy_id = 1;

1 row updated.
"

Remove the reservation. SQL> DELETE FROM 2 WHERE 1 row deleted. reservation member_id = 101;

A144

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
6c.continued
"

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 The Glob My Day Off Miracles on Ice Soda Gang Interstellar Wars Alien Again My Day Off Interstellar Wars My Day Off 11 rows selected. 1 1 1 1 1 1 AVAILABLE AVAILABLE AVAILABLE AVAILABLE AVAILABLE RENTED

08-FEB-96 12-FEB-96

2 RENTED 2 AVAILABLE 2 AVAILABLE

11-FEB-96

3 RENTED

10-FEB-96

Practice Solutions

A145

Practice 17 Solutions
7.

continued

Make a modification to one of the tables.


a.

Add a PRICE column to the TITLE table to record the purchase price of the video. The column should have a total length of eight digits and two decimal places. Verify your modification. SQL> ALTER TABLE title 2 ADD (price NUMBER(8,2)); Table altered.

SQL> DESCRIBE title Name -------------------------TITLE_ID TITLE DESCRIPTION RATING CATEGORY RELEASE_DATE PRICE Null? -------NOT NULL NOT NULL NOT NULL Type ---NUMBER(10) VARCHAR2(60) VARCHAR2(400) VARCHAR2(4) VARCHAR2(20) DATE NUMBER(8,2)

A146

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
7.continued b.

continued

Create a script named p17q7b.sql to update each video with a price according to the following list: Price 25 35 35 35 98 35 29

Title Willie and Christmas Too Alien Again The Glob My Day Off Miracle on Ice Soda Gang Interstellar Wars
"

Script p17q7b.sql contents. SET ECHO OFF UPDATE title SET price = &price WHERE title_id = &title_id / SET ECHO ON

SQL> START p17q7b SET ECHO OFF Enter value for price: 25 Enter value for title_id: 92 1 row updated.

Practice Solutions

A147

Practice 17 Solutions
7b.continued

continued

SQL> START p17q7b SET ECHO OFF Enter value for price: 35 Enter value for title_id: 93 1 row updated.

SQL> START p17q7b SET ECHO OFF Enter value for price: 35 Enter value for title_id: 94 1 row updated.

SQL> START p17q7b SET ECHO OFF Enter value for price: 35 Enter value for title_id: 95 1 row updated.

SQL> START p17q7b SET ECHO OFF Enter value for price: 98 Enter value for title_id: 96 1 row updated.

A148

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
7b.continued

continued

SQL> START p17q7b SET ECHO OFF Enter value for price: 35 Enter value for title_id: 97 1 row updated.

SQL> START p17q7b SET ECHO OFF Enter value for price: 29 Enter value for title_id: 98 1 row updated.

SQL> COMMIT; Commit complete.


"

Verify the changes. SQL> SELECT title_id, title, price 2 FROM title 3 ORDER BY title_id;

Practice Solutions

A149

Practice 17 Solutions
7b.continued

continued

TITLE_ID TITLE PRICE ---------- --------------- ---------92 Willie and 25 Christmas Too 93 94 95 96 97 98 Alien Again The Glob My Day Off Miracles on Ice Soda Gang Interstellar Wars 35 35 35 98 35 29

7 rows selected.
c.

Ensure that in the future all titles will contain a price value. Verify the constraint. SQL> ALTER TABLE 2 MODIFY 3 Table altered. title (price CONSTRAINT member_price_nn NOT NULL);

SQL> SELECT 2 3 FROM 4 WHERE

constraint_name, constraint_type, search_condition, r_constraint_name user_constraints table_name = TITLE;

A150

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
7c.continued

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

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.

Practice Solutions

A151

Practice 17 Solutions
8.

continued

Create a report titled Customer History Report. This report will contain each customer 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 total number of rentals for all customers for the reporting period. Save the script in a file named p17q8.sql. SET ECHO OFF SET PAGESIZE 30 SET LINESIZE 52 TTITLE Customer History Report COLUMN member FORMAT A17 COLUMN title FORMAT A15 WORD_WRAPPED COLUMN book_date FORMAT A9 COLUMN duration FORMAT 9999999 BREAK ON member skip 1 ON REPORT COMPUTE COUNT LABEL Total Rentals OF title ON REPORT SELECT m.first_name|| ||m.last_name MEMBER, t.title, r.book_date, r.act_ret_date - book_date DURATION FROM member m, title t, rental r WHERE r.member_id = m.member_id AND r.title_id = t.title_id ORDER BY m.last_name / CLEAR COMPUTE CLEAR BREAK COLUMN duration CLEAR COLUMN book_date CLEAR COLUMN title CLEAR COLUMN member CLEAR SET PAGESIZE 25 SET LINESIZE 80 SET ECHO ON

A152

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 17 Solutions
8.continued

continued

Sat Feb 10 Customer History Report

page

MEMBER TITLE BOOK_DATE DURATION ----------------- --------------- --------- -------LaDoris Ngao My Day Off 08-FEB-96 Molly Urguhart Carmen Velasquez Soda Gang Willie and Christmas Too Interstellar Wars Alien Again ***************** --------------Total Rentals 5 06-FEB-96 07-FEB-96 2 1

10-FEB-96

09-FEB-96

Practice Solutions

A153

Practice 19 Solutions
1.

Load and execute a loop counter. Launch Procedure Builder. Your instructor will give you the login information. 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.
a.

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) IS BEGIN 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 IS BEGIN TEXT_IO.PUT_LINE (Hello World); END;

b. c.

Compile the procedure using the Program Unit Editor. Execute the procedure from the Interpreter pane. PL/SQL> my_message;

A154

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 20 Solutions
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. b. c. d.

Header Declarative Executable Exception handling

Practice Solutions

A155

Practice 20 Solutions
6.

continued

Create a procedure called MY_PROCEDURE to output the phrase My Procedure 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 the Procedure radio button. Click OK.

"

In the Program Unit Editor window, select all the skeleton text. From the menu, select Edit/Import. Choose the LABS\p20proc.pls file. Click OK.

PROCEDURE my_procedure IS TEXT_IO.PUTLINE (My Procedure Works) END;

A156

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 20 Solutions
6.continued b.

continued

Compile the code. Make appropriate corrections so code successfully compiles.


" " " "

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

Practice Solutions

A157

Practice 21 Solutions
1.

Evaluate each of the following declarations. Determine which of them are not legal and explain why. DECLARE v_id
a.

NUMBER (4);

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

A158

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 21 Solutions
2.

continued

Suppose you embed a sub-block within a block, as depicted below. You declare two 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
"

f.

V_NAME is not visible in the main block and you would see an error. The value of V_CREDIT_RATING within the main block is
" "

EXCELLENT.

DECLARE v_customer VARCHAR2(50) := Womansport; v_credit_rating VARCHAR2(10) := EXCELLENT; BEGIN SUB-BLOCK DECLARE v_customer v_name BEGIN v_customer END; v_customer v_name v_credit_rating NUMBER (7) := 201; VARCHAR2(25):= Unisports; v_name v_credit_rating

Scope Example

END;

Practice Solutions

A159

Practice 21 Solutions
3.

continued

Create and execute a procedure named MULTIPLIER that accepts two numbers through variables. The first number should be divided by the second number and have the second number added to the result. The result should be written to a PL/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

A160

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 21 Solutions
4.

continued

Build a function named ANN_COMP that computes the total compensation for one year. The annual salary and the annual bonus percentage will be passed to the function, and the bonus will need to be converted from a whole number to a decimal (for example, 15 to .15). If the salary is null, set it to zero before computing the total compensation. Likewise, if the bonus is null, set it to zero before computing the total compensation. Execute the function. Reminder: Use the NVL function to handle null values.
"

Solution file: SOLN\p21q4.pls FUNCTION ann_comp (v_salary IN NUMBER, v_bonus IN NUMBER) RETURN NUMBER IS 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 output variable value. PL/SQL> .CREATE NUMBER g_comp PRECISION 10 SCALE 2 PL/SQL> :g_comp := ann_comp (50000,10); PL/SQL> TEXT_IO.PUT_LINE (TO_CHAR(:g_comp)); 55000

Practice Solutions

A161

Practice 21 Solutions
5.

continued

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 NUMBER IS 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 output variable 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

A162

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 22 Solutions
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. b. c.
"

Use the S_DEPT_ID sequence generator for the department number. Create a parameter for the department name. Leave the region number null for now. Solution file: SOLN\p22q1.pls PROCEDURE new_dept (v_dept_name IN VARCHAR2) IS BEGIN 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 +> WHERE * s_dept name = Health;

ID NAME REGION_ID -------- ------------------------- --------51 Health 1 row selected.

Practice Solutions

A163

Practice 22 Solutions
2. a. b. c.
"

continued

Create a procedure to update the region number for an existing department. Create a parameter for the department number. Create a parameter for the region name. Set the region number to the value that corresponds to the specified region name. 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 not exist? PL/SQL> update_dept (51, Europe);
"

If the operator enters an invalid region name, the NO_DATA_FOUND exception is raised.

A164

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 22 Solutions
2.continued e.

continued

Display the department number, region number, and region name for the updated department. PL/SQL> +> +> +> SELECT FROM WHERE AND d.id, d.region_id, r.name s_dept d, s_region r d.region_id = r.id 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. b.

Create a parameter for the department number. 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;

Practice Solutions

A165

Practice 22 Solutions
3.continued c.

continued

Test the procedure. What happens if you enter a department number that does not exist? PL/SQL> delete_dept (51); If the operator enters a department number that does not exist, the procedure completes successfully because this does not constitute an exception. What happens if you enter a department that has employees?
" "

The Oracle7 Server sends an error message that an integrity constraint has been violated.

d.

Confirm that the department has been deleted. PL/SQL> SELECT +> FROM +> WHERE No rows selected. * s_dept id = 51;

e.

Test the procedure. PL/SQL> delete_dept (51);

A166

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 22 Solutions
4.

continued

Create a procedure named NEW_EMP to insert a new employee into the S_EMP table.
a. b. c. d. e.

Create parameters for first name, last name, and job title. Use the S_EMP_ID sequence generator for the employee number. Compute the user ID by concatenating the first letter of the first name with the first seven letters of the last name, and converting all letters to lowercase. Set the start date to the current date. 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 several people are tied for lowest-paid, choose any one of them.) Leave the comments and the commission percent empty. Solution file: SOLN\p22q4.pls Code has been formatted to fit page.

f.
"

Practice Solutions

A167

Practice 22 Solutions
4.continued

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;

A168

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 22 Solutions
4.continued
"

continued

Execute the procedure.

PL/SQL> new_emp (Jayne,Bowman, 2> Sales Representative);


g.

Verify the record has been added by viewing the employees 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

Practice Solutions

A169

Practice 23 Solutions
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 commission percentage for a given employee based upon total sales.
a.

Prepare this exercise by disabling the constraint on the COMMISSION_PCT column in the S_EMP table. You modify the commission percentage to values that are not in the constraint. PL/SQL> ALTER TABLE s_emp +> DROP CONSTRAINT s_emp_commission_pct_ck;

b. c. d. e. f. g. h. i.

Create a parameter to accept the employee number from the user. Find the sum of the totals for all orders placed by that employee. If the sum is less than 100,000, set the commission percentage for the employee to 10. If the sum is between 100,000 and 1,000,000 inclusive, set the commission percentage for the employee to 15. If the sum exceeds 1,000,000, set the commission percentage for the employee to 20. If no orders appear in the S_ORD table for the given employee, set the commission percentage to 0. Commit the change. Test the block and view the changes. Results should appear for some example employees as follows. Employee Number 1 11 12 14 Total Sales 0 1,629,066.37 100,184.00 16,358.00 Resulting Commission 0 20 15 10

A170

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 23 Solutions
1.continued
"

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;

Practice Solutions

A171

Practice 23 Solutions
1.continued

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 the customer s credit rating is already Excellent), otherwise set the credit rating to Good. Once the rows are updated, find out how many rows were updated. Print the following statements to the screen based on the number of rows updated.
i.

b.

If less than three rows updated, statement should read Fewer than 3 customer records updated for region number X, where X represents the region number. Otherwise, it should read Y rows updated for region number X, where Y is the number of rows updated, and X is the region number.

ii.

A172

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 23 Solutions
2.continued
" "

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 for region 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 Interpreter prompt. Observe the resulting statements.

Practice Solutions

A173

Practice 23 Solutions
2.continued c.

continued

Rollback the changes. Set a breakpoint on the conditional test for the number of rows updated. Execute the procedure. Check the Stack node to verify the values of the variables as you Step Into the statements in the loop. Reminder: You can use the Quick Tour, Debugging a Program Unit section for assistance.
"

"

Issue a ROLLBACK statement to undo changes. In the Navigator, click the CUST_UPDATE program unit. In the Interpreter source pane, double-click the line with the statement IF v_updated < 3 THEN to set the breakpoint. Execute the procedure again. When the breakpoint is reached, investigate the values in the Stack node of the Navigator as you step into 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 a message 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. Message Salary more than 1200 Name contains R March start date **None**

Criteria Salary greater than 1200 Last name contains r Start date is in March None of the above
" "

Solution file: SOLN\p23q3.pls In the Navigator, create a new procedure. Name it EMP_MESSAGE.

A174

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 23 Solutions
3.continued

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;

Practice Solutions

A175

Practice 23 Solutions
3.continued
"

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 - March start 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**

A176

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 24 Solutions
1.

Create a procedure named TOP_DOGS1 that determines the top employees with respect to salaries.
a.

Prepare for this exercise by creating a new table for storing employees and their salaries. PL/SQL> CREATE TABLE top_dogs +> (name VARCHAR2(25), +> salary NUMBER(11,2));

b. c. d. e. f. g.

Add a parameter to accept the user input n for the top number of employees. 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. Store the names and salaries in the TOP_DOGS table. Assume for the moment that no two employees have the same salary. Test the exercise under a variety of special cases, such as n = 0, n is greater than the number of employees in the S_EMP table. Empty the TOP_DOGS table after each test.

Practice Solutions

A177

Practice 24 Solutions
1.continued
" "

continued

Solution file: SOLN\p24q1.pls From the Tools menu, select Stored Program Unit Editor... Set the Owner to your username, and click the New button. Create a new procedure. Name it TOP_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.00 Ropeburn 1550.00 Nguyen 1525.00 Sedeghi 1515.00 4 rows selected.

A178

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 24 Solutions
1.continued
"

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.

Practice Solutions

A179

Practice 24 Solutions
1.continued
"

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.00 Ropeburn 1550.00 Nguyen 1525.00 Sedeghi 1515.00 Giljum 1490.00 Ngao 1450.00 Dumas 1450.00 Quick-To-See 1450.00 Nagayama 1400.00 Bowman 1400.00 Magee 1400.00 Maduro 1400.00 Havel 1307.00 Catchpole 1300.00 Menchu 1250.00 Urguhart 1200.00 Nozaki 1200.00 Biri 1100.00 Schwartz 1100.00 Smith 940.00 Dancs 860.00 Markarian 850.00 Chang 800.00 Patel 795.00 Patel 795.00 Newman 750.00 26 rows selected.

A180

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 24 Solutions
2.

continued

Create a stored procedure named ADD_STARS to reward all employees by appending 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 for storing asterisks (*). PL/SQL> ALTER TABLE s_emp +> ADD stars VARCHAR2(100);

b.

Determine the commission percentage for the employee, rounded to the nearest whole number. Also, consider the case where the employee has no commission percent. Add an asterisk to a string of asterisks for every commission point. For example, if the employee has a commission percentage of 10, then the STARS column will contain ten asterisks. Update the STARS column for each employee with the string of asterisks.

c.

d.

Practice Solutions

A181

Practice 24 Solutions
2.continued
" "

continued

Solution file: SOLN\p24q2.pls From the Tools menu, select Stored Program Unit Editor... Set the Owner to your username, and click the New button. Create a new procedure. Name it ADD_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;

A182

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 24 Solutions
2.continued
"

continued

Execute the procedure to put in the stars, and confirm the changes to the table. PL/SQL> PL/SQL> +> +> add_stars; SELECT FROM WHERE

id, commission_pct, stars s_emp 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 several employees in the exercise 1 have the same salary. For each name listed, all names having 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, then Nagayama, Magee, and Maduro should all display. Remember to empty the TOP_DOGS table after each test.

Practice Solutions

A183

Practice 24 Solutions
3.continued
" "

continued

Solution file: SOLN\p24q3.pls In the Navigator, select the TOP_DOGS1 procedure. From the menu, choose Edit>Duplicate. Open the copy of TOP_DOGS1_XXX, where XXX represents 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;

A184

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 24 Solutions
3.continued
"

continued

Execute the procedure. PL/SQL> top_dogs2(7); PL/SQL> SELECT * FROM top_dogs; NAME SALARY -------------------- ------------Velasquez 2500.00 Ropeburn 1550.00 Nguyen 1525.00 Sedeghi 1515.00 Giljum 1490.00 Ngao 1450.00 Dumas 1450.00 Quick-To-See 1450.00 8 rows selected.

PL/SQL> top_dogs2(10); PL/SQL> SELECT * FROM top_dogs; NAME SALARY -------------------- ------------Velasquez 2500.00 Ropeburn 1550.00 Nguyen 1525.00 Sedeghi 1515.00 Giljum 1490.00 Ngao 1450.00 Dumas 1450.00 Quick-To-See 1450.00 Nagayama 1400.00 Bowman 1400.00 Magee 1400.00 Maduro 1400.00 12 rows selected.

Practice Solutions

A185

Practice 25 Solutions
1.

Modify the procedure to handle exceptions. The procedure tries to update region numbers for existing departments.
a.

Load the LABS\p25q1a.pls script file. Note: The procedure UPDATE_DEPT2 is 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. d.

Write an exception handler for the error to pass a message to the user that the specified region does not exist. Execute the procedure by entering the following text. PL/SQL> update_dept2 (31,Asia);

e. f.

Write an exception handler for the error to pass a message to the user that the specified region already has a department of that name. 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 the specified department number does not exist. Reminder: The SQL attribute %NOTFOUND and raise an exception manually.

A186

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 25 Solutions
1.continued
" "

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;

Practice Solutions

A187

Practice 25 Solutions
1.continued
"

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.

A188

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 25 Solutions
2.

continued

Write a procedure named SALARY_RANGE that prints the names of the employees that make plus or minus 100 dollars of the salary value entered.
a. b.

If there is no employee within that salary range, then print a message to the user indicating that is the case. Use an exception for this case. If there are more than 3 employees within that range, then the message should indicate how many employees have that salary range. Your results should look like the list below. Results have 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.

"

Solution file: SOLN\p25q2.pls " In the Navigator, create a new procedure. Name it SALARY_RANGE.

Practice Solutions

A189

Practice 25 Solutions
2.continued

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.

A190

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 25 Solutions
2.continued

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.

Practice Solutions

A191

Practice 26 Solutions
1.

Complete the database design by writing subprograms to perform the following actions.
a.

Create a function named NEW_MEMBER to return the membership number for that new member. Be sure to use a sequence generator to create the unique member 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;

"

A192

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 26 Solutions
1.continued b.

continued

Create a function named NEW_RENTAL to record a new rental based on a member s last name. Return a message with the expected due date. If two or more 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.

"

Practice Solutions

A193

Practice 26 Solutions
1b.continued

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;

A194

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 26 Solutions
1.continued c.
"

continued

Create a procedure named MEM_TITLES to retrieve all the titles rented by a member. 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;

Practice Solutions

A195

Practice 26 Solutions
1.continued d.
"

continued

If a title is rented, create a reservation for that movie. Name your procedure RESERVE_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;

A196

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 26 Solutions
1.continued e.

continued

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 RESULTS table. Check the to see if there are reservations for the film title, and store a message 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.

Practice Solutions

A197

Practice 26 Solutions
1e.continued

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;

A198

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 26 Solutions
1.continued f.

continued

If a video is returned damaged, change its status to DAMAGED. If that copy was the only copy owned by the store, store a message to buy another copy in the RESULTS table. If only one copy remains for rental, store a warning that only one copy is left for rental in the RESULTS table. Name your procedure DAMAGED_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.

"

Practice Solutions

A199

Practice 26 Solutions
1f.continued

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;

A200

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice 26 Solutions
1.continued g.

continued

Create a procedure named TOP_RENTAL to determine the top rental. Allow for more than one top rental. Store the names and a message of the top rentals in 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;

"

Practice Solutions

A201

A202

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

B
Table Descriptions and Data

B2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summit Sporting Goods Database Diagram


ORD_ID

S_ITEM
PRODUCT_ID

ID

S_ORD
CUSTOMER_ID

SALES_REP_ID

S_INVENTORY
PRODUCT_ID ID ID ID ID

S_CUSTOMER
SALES_REP_ID

S_PRODUCT
IMAGE_ID

S_WAREHOUSE
REGION_ID MANAGER_ID ID ID

ID

ID

S_IMAGE

S_EMP
MANAGER_ID DEPT_ID ID

S_DEPT
REGION_ID ID ID ID

S_REGION

Unique occurrences are identified by PRODUCT_ID and WAREHOUSE_ID.

Table Descriptions and Data

B3

S_CUSTOMER Table
SQL> DESCRIBE s_customer

Name ID NAME PHONE ADDRESS CITY STATE COUNTRY ZIP_CODE CREDIT_RATING SALES_REP_ID REGION_ID COMMENTS

Null? NOT NULL NOT NULL

Type NUMBER(7) VARCHAR2(50) VARCHAR2(25) VARCHAR2(400) VARCHAR2(30) VARCHAR2(20) VARCHAR2(30) VARCHAR2(75) VARCHAR2(9) NUMBER(7) NUMBER(7) VARCHAR2(255)

Note: The data on the pages to follow has been formatted. Use the provided table descriptions for accurate column names.

B4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_CUSTOMER Table
SQL> SELECT * FROM s_customer;

continued

Continued on Next Page

Table Descriptions and Data

B5

S_CUSTOMER Table

continued

B6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_DEPT Table
SQL> DESCRIBE s_dept

Name ID NAME REGION_ID

Null?

Type

NOT NULL NUMBER(7) NOT NULL VARCHAR2(25) NUMBER(7)

SQL> SELECT * FROM s_dept;

Table Descriptions and Data

B7

S_EMP Table
SQL> DESCRIBE s_emp

Name ID LAST_NAME FIRST_NAME USERID START_DATE COMMENTS MANAGER_ID TITLE DEPT_ID SALARY COMMISSION_PCT

Null?

Type

NOT NULL NUMBER(7) NOT NULL VARCHAR2(25) VARCHAR2(25) NOT NULL VARCHAR2(8) DATE VARCHAR2(255) NUMBER(7) VARCHAR2(25) NUMBER(7) NUMBER(11,2) NUMBER(4,2)

B8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_EMP Table
SQL> SELECT * FROM s_emp;

continued

Table Descriptions and Data

B9

S_IMAGE Table
SQL> DESCRIBE s_image

Name ID FORMAT USE_FILENAME FILENAME IMAGE

Null?

Type

NOT NULL NUMBER(7) VARCHAR2(25) VARCHAR2(25) VARCHAR2(25) LONG RAW

SQL> SELECT * FROM s_image;

B10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_INVENTORY Table
SQL> DESCRIBE s_inventory

Name

Null?

Type NUMBER(7) NUMBER(7) NUMBER(9) NUMBER(9) NUMBER(9) VARCHAR2(255) DATE

PRODUCT_ID NOT NULL WAREHOUSE_ID NOT NULL AMOUNT_IN_STOCK REORDER_POINT MAX_IN_STOCK OUT_OF_STOCK_EXPLANATION RESTOCK_DATE

Table Descriptions and Data

B11

S_INVENTORY Table
SQL> SELECT * FROM s_inventory;

continued

Continued on Next Page

B12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_INVENTORY

continued

Continued on Next Page

Table Descriptions and Data

B13

S_INVENTORY

continued

Continued on Next Page

B14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_INVENTORY

continued

Table Descriptions and Data

B15

S_ITEM Table
SQL> DESCRIBE s_item

Name ORD_ID ITEM_ID PRODUCT_ID PRICE QUANTITY QUANTITY_SHIPPED

Null?

Type

NOT NULL NUMBER(7) NOT NULL NUMBER(7) NOT NULL NUMBER(7) NUMBER(11,2) NUMBER(9) NUMBER(9)

B16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_ITEM Table
SQL> SELECT * FROM s_item;

continued

Continued on Next Page

Table Descriptions and Data

B17

S_ITEM Table

continued

Continued on Next Page

B18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_ITEM Table

continued

Table Descriptions and Data

B19

S_ORD Table
SQL> DESCRIBE s_ord

Name ID CUSTOMER_ID DATE_ORDERED DATE_SHIPPED SALES_REP_ID TOTAL PAYMENT_TYPE ORDER_FILLED

Null?

Type

NOT NULL NUMBER(7) NOT NULL NUMBER(7) DATE DATE NUMBER(7) NUMBER(11,2) VARCHAR2(6) VARCHAR2(1)

B20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_ORD Table
SQL> SELECT * FROM s_ord;

continued

Table Descriptions and Data

B21

S_PRODUCT Table
SQL> DESCRIBE s_product

Name ID NAME SHORT_DESC LONGTEXT_ID IMAGE_ID SUGGESTED_WHLSL_PRICE WHLSL_UNITS

Null?

Type

NOT NULL NUMBER(7) NOT NULL VARCHAR2(50) VARCHAR2(255) NUMBER(7) NUMBER(7) NUMBER(11,2) VARCHAR2(25)

B22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_PRODUCT Table
SQL> SELECT * FROM s_product;

continued

Continued on Next Page

Table Descriptions and Data

B23

S_PRODUCT Table

continued

B24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

S_REGION Table
SQL> DESCRIBE s_region

Name ID NAME

Null?

Type

NOT NULL NUMBER(7) NOT NULL VARCHAR2(50)

SQL> SELECT * FROM s_region;

Table Descriptions and Data

B25

S_WAREHOUSE Table
SQL> DESCRIBE s_warehouse

Name ID REGION_ID ADDRESS CITY STATE COUNTRY ZIP_CODE PHONE MANAGER_ID

Null? NOT NULL NOT NULL

Type NUMBER (7) NUMBER (7) LONG VARCHAR2 (30) VARCHAR2 (20) VARCHAR2 (30) VARCHAR2 (75) VARCHAR2 (25) NUMBER (7)

SQL> SELECT * FROM s_warehouse;

ID REGION_ID _____ ___________ 101 1 10501 5 201 2 301 3 401 4 COUNTRY __________________ USA CZECHOZLOVAKIA Brazil Nigeria

ADDRESS _______________ 283 King Street 5 Modrany 68 Via Centrale 6921 King Way 86 Chu Street ZIP_CODE __________

CITY ______________ SEATTLE BRATISLAVA SAO PAOLO LAGOS HONG KONG PHONE _________

STATE _______ WA

MANAGER_ID _____________ 6 10 7 8 9

Note: Table has been split into two parts to make it fit in the page.

B26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

C
Using SQL*Plus to Create Reports and Manage PL/SQL Code

C2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Objectives
This lesson covers formatting query output to produce simple reports, controlling the SQL*Plus environment, and manipulating PL/SQL code using SQL*Plus. At the end of this lesson, you should be able to
D D D D

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 the online editor. Execute SQL*Plus commands, anonymous blocks, program units, and SQL statements. Compile procedures and functions. Embed messages to assist with debugging code.

D D

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C3

The SQL*Plus Environment

C4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Overview
SQL*Plus is an environment in which you can
D

Execute SQL statements to retrieve, modify, add, and remove data from database tables. Format, perform calculations on, store, and print query results in the form of reports. Issue SQL statements to create, alter, and remove database tables. Create anonymous blocks, subprograms, database triggers using procedural language extension, PL/SQL.

D D

SQL*Plus has a variety of commands you need to use to execute subprograms, pass values in and out of PL/SQL blocks, and debug your code. SQL*Plus commands may be divided into the following main categories. Category Environment Format File manipulation Execution Edit Interaction Purpose Affects the general behavior of SQL statements for the session. Formats query results. Saves, loads, and runs script files. Sends SQL or PL/SQL commands from SQL buffer to Oracle7 Server. Modifies SQL commands in the buffer. Allows users to create and pass variables to SQL statements, print variable values, and print messages to the screen. Various commands to connect to the database, manipulate the SQL*Plus environment, and display column definitions.

Miscellaneous

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C5

Entering Commands in SQL*Plus

C6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Entering Commands in SQL*Plus


Once you log in to SQL*Plus, you see the command prompt. Issue all your commands at this prompt. Three types of commands can be entered at this prompt.
D D

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 do not need to be terminated with a semicolon (;). SQL statements and PL/SQL blocks do need to be terminated with a semicolon to send the statement to the Oracle7 Server.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C7

C8

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Comparison of SQL and SQL*Plus Commands


This table compares SQL and SQL*Plus commands. They are distinctly different programs, but are used together to perform some tasks, such as to format data in a report and to control command files. SQL Is a language for communicating with the Oracle Server to access data. Is based on American National Standards Institute (ANSI) standard SQL. SQL*Plus Recognizes SQL commands, and sends them to the server. Is the Oracle proprietary interface for executing SQL commands.

Manipulates data and table definitions in Does not allow you to manipulate values the database. in the database. Is entered into the SQL*Buffer on one or Is entered one line at a time; not stored more lines. in the SQL buffer. Does not have a continuation character. Has a dash - as a continuation character if the command is longer than one line. Can be abbreviated. Does not require termination characters; commands are immediately executed. Uses commands to format data.

Cannot be abbreviated. Uses a termination character to execute commands required. Uses functions to perform some formatting.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C9

C10

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL*Plus SET Commands


Control the environment in which SQL*Plus is currently operating by using the SET commands. Syntax SET system_variable value where: system_variable value is a variable that controls one aspect of the session environment. is a value for the system variable.

Default Settings Using the login.sql File The login.sql file contains standard SET and other SQL*Plus commands that you may require for every session. The file is read and commands are implemented at log in. When you log out of your session, all customized setting are lost. Changing the Default Settings 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 settings are lost. Add permanent changes to settings to the login.sql file. For more information, see SQL*Plus Users Guide and Reference, Release 3.3, Command Reference.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C11

C12

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

SQL* Plus SET Commands


Some Useful SET Commands SET Variable and Values ARRAY[SIZE] {20|n} COLSEP { |text} FEED[BACK] {6|n|OFF|ON} HEA[DING]{OFF|ON} LIN[ESIZE] {80|n} LONG {80|n} PAGES[IZE] {24|n} PAU[SE] {OFF|ON|text} TERM[OUT] {OFF|ON} Description Sets the database data fetch size. Sets text to be printed between columns. Default is single space. Displays the number of records returned by a query when the query selects at least n records. Determine whether column headings are displayed in reports. Sets the number of characters per line to n for reports. Sets maximum width for displaying LONG values. Specifies the number of lines per page of output. Allows you to control scrolling of your terminal. You must press [Return] after seeing each pause. Determines whether output is displayed to the screen.

Guidelines
D

Use the SHOW command to view current values for any of these settings, for example SHOW PAUSE. To see all SET variable values, use the SHOW ALL command. The value n represents a numeric value. Underlined values shown above indicate default values. If you enter no value with the variable, then SQL*Plus assumes the default value.

D D

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C13

C14

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Report
Script File You can create a script file (or command file) that includes both a SQL SELECT statement and SQL*Plus commands used to format and reset command values. Script files are useful for saving both a SQL statement and any SQL*Plus settings specific to 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 executed from within your command file. SQL*Plus Format Commands You can control the report features described above by using the following commands: Command COL[UMN] [column option] TTI[TLE] [text|OFF|ON] BTI[TLE] [text|OFF|ON] Purpose Controls column formats. Specifies a header to appear at the top of each page of the report. Specifies a footer to appear at the bottom of each page of the report.

Guidelines
D

All format commands remain in effect until the end of the SQL*Plus session, or until 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; you must 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 the column name.

D D

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C15

C16

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Report
TTITLE and BTITLE Commands

continued

Use the TTITLE command to format page headers and the BTITLE command for footers. Footers appear at the end of the page according to the PAGESIZE value. Syntax 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 text variable Example Set the report header to display Salary centered on one line, and Report centered below it. SQL> TTITLE Salary|Report is an option to specify the type of settings. represents the title text. Enter single quotes if the text is more than one word. is a system-maintained value.

Display or Clear Settings To show or clear the current header and footer command settings, use the following commands. Command TTITLE TTITLE OFF BTITLE BTITLE OFF Description Displays the current setting for the header. Turns the header off. Displays the current setting for the footer. Turns the footer off.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C17

C18

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Report
Creating the Script File to Run a Report

continued

You can either enter each of the SQL*Plus commands at the SQL prompt or put all the commands, including the SELECT statement, in a command (or script) file. A typical script consists of at least one SELECT statement and several SQL*Plus commands. Steps to Create a Script File
1.

Create the SQL SELECT statement at the SQL prompt. Ensure that the data required for the report is accurate before you save the statement to a file and apply formatting commands. Ensure that the relevant ORDER BY clause is included if you intend to use breaks. Save the SELECT statement to a script file. Edit the script file to enter the SQL*Plus commands. Add the required formatting commands before the SELECT statement. Be certain not to place SQL*Plus commands within the SELECT statement. Verify that the SELECT statement is followed by a run character, either a semicolon (;) or a slash (/). Add the format-clearing SQL*Plus commands after the run character. As an alternative, you can call a reset file which contains all the format-clearing commands. Save the script file with your changes. In SQL*Plus, run the script file by entering START filename or @filename. This command is required to read and execute the script file.

2. 3. 4. 5. 6.

7. 8.

Guidelines
D D D

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 original SQL*Plus environment.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C19

1 2

1 Header

2 Column labels and format

3 Footer

C20

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Creating a Report

continued

Example Create a script file to create a report which displays the job title, last name, and salary for every employee who is not a vice president or a warehouse manager. Add a centered, two-lined header that reads Employee Report, and a centered footer that reads 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 with the label in initial capitalization and formatted as $2,500.00. REM ** This report covers all employees who are not REM ** vice presidents or warehouse managers. SET ECHO OFF SET PAGESIZE 37 SET LINESIZE 60 SET FEEDBACK OFF TTITLE Employee|Report BTITLE Confidential COLUMN title HEADING Job|Category FORMAT A22 COLUMN last_name HEADING Employee FORMAT A22 COLUMN salary HEADING Salary FORMAT $99,999.99 REM ** Insert SELECT statement SELECT title, last_name, salary FROM s_emp WHERE title NOT LIKE VP% AND title <> Warehouse Manager ORDER BY title, last_name, salary / REM ** Run a reset command file START reset.sql SET ECHO ON REM represents a remark or comment in SQL*Plus.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C21

Declaring and Creating PL/SQL Blocks

C22

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Declaring and Creating PL/SQL Blocks


You can use two methods to process PL/SQL blocks in SQL*Plus.
D D

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.

Declaring PL/SQL Blocks in the SQL Buffer A PL/SQL block is treated as one continuous statement in the buffer, and the semicolons (;) 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 or BEGIN at the prompt. You can close the buffer without executing the block by entering a period (.) at the number prompt of the buffer. To run the buffered PL/SQL block, enter the RUN command or a slash (/) at the prompt. If the block executes successfully, without unhandled exceptions or compile errors, you will see a message. Creating SQL*Plus Files Containing PL/SQL Blocks You can include PL/SQL blocks in files of SQL and SQL*Plus commands. Create the file using the operating system editor. SQL*Plus commands may not occur inside the PL/SQL block itself, but you can include them elsewhere in the file. You can reference SQL*Plus substitution variables inside the block, but remember that they are substituted with the variables contents before the code is parsed or executed. This means that if you reference a SQL*Plus substitution variable in a PL/SQL loop, then a value is substituted for the variable once, and not for each iteration of the loop.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C23

SQL*Plus Commands

C24

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Entering Commands in SQL*Plus


SQL*Plus contains an array of commands to format reports and initiate the users environment. SQL*Plus Command ACCEPT VARIABLE PRINT EXECUTE Description Reads input from the user and stores the input into a variable. Declares a bind, or host, variable that can be referenced in PL/SQL with a preceding colon (:). Displays the current value of bind variables. Executes a single PL/SQL statement.

For more information, see SQL*Plus User s Guide and Reference, Release 3.3.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C25

C26

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Passing Input and Output Values


A substitution variable, or parameter, preceded by an ampersand (&) is used to represent 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. Input Values From SQL*Plus, input a value into the PL/SQL block by means of a SQL*Plus substitution value. Follow the steps listed below.
1. 2.

Outside the PL/SQL block, assign a value from the keyboard into a SQL*Plus substitution value with the SQL*Plus ACCEPT command. Within the PL/SQL block, embed the SQL*Plus substitution parameter wherever it is needed as input, referencing it with the ampersand (&) prefix.

Syntax ACCEPT variable PROMPT message where: variable message is the name of the substitution variable to store the value. is the message displayed.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C27

C28

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Passing Input and Output Values


Output Values

continued

Output a value from the PL/SQL block into SQL*Plus by using a SQL*Plus global variable. Follow the steps listed below.
1. 2. 3.

Outside the PL/SQL block, declare a SQL*Plus global variable with the SQL*Plus VARIABLE command. Within the PL/SQL block, embed the SQL*Plus global variable wherever it is needed as output, referencing it with the colon (:) prefix. Outside the PL/SQL block, print the output value on the screen with the SQL*Plus PRINT command.

Syntax VARIABLE variable [NUMBER|CHAR|CHAR(n)|VARCHAR2(n)]

PRINT variable where: variable n is the name of the bind variable. is the maximum length for the datatype.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C29

C30

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Debugging in SQL*Plus
When you execute your PL/SQL code, one of two types of errors might appear. One type is a compilation error. For anonymous blocks, you will see the errors appear on the screen. For stored subprograms, the compilation errors are stored in the USER_ERRORS data dictionary table. To access those errors, enter either of the following 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 from the PL/SQL engine indicating that an error occurred while performing some of the tasks in the block. Handling of exceptions is covered in lesson 25 of this course.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C31

C32

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Debugging in SQL*Plus

continued

One method for debugging your PL/SQL block using SQL*Plus is to embed global variables at specific points with a message. Each message can contain information about how many times a loop was executed, or which statements were executed. You can print the results of the global variables using the SQL*Plus PRINT command. Example 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.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C33

C34

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Displaying Contents of a Subprogram


You can obtain the text of a stored procedure or a function from USER_SOURCE data dictionary view. Example Display contents of the procedure CHANGE_SALARY. SQL> SELECT 2 FROM 3 WHERE 4 and text user_source type = PROCEDURE name = CHANGE_SALARY;

TEXT PROCEDURE change_salary (v_emp_id IN NUMBER, v_new_salary IN NUMBER) IS BEGIN UPDATE s_emp SET salary = v_new_salary WHERE id = v_emp_id; COMMIT; END change_salary;

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C35

C36

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Executing Stored Subprograms


Once you create your stored programs, you invoke them by using the SQL*Plus EXECUTE command. Executing Stored Procedures The EXECUTE command runs the PL/SQL statement stored in the database. Syntax EXECUTE procedure_name [(argument_list)] where: procedure_name argument_list Executing Stored Functions Functions require that a value be returned. Therefore, you call the function as part of an expression. Create a global variable to hold the returned value when using the EXECUTE command. Syntax EXECUTE variable := function_name [(argument_list)] where: procedure_name argument_list is the name of the function. is the set of variables, expressions, constants, or literals passed to the function. is the name of the procedure. is the set of variables, expressions, constants, or literals passed to the procedure.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C37

C38

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Executing Stored Subprograms


Issue SQL commands and evaluate PL/SQL constructs. Example

continued

Enter a data definition language (DDL) statement at the command prompt to create the B_TEST table. SQL> CREATE TABLE b_test (col1 NUMBER); Insert three rows in the B_TEST table using a PL/SQL statement. SQL> 2 3 4 5 6 7 CREATE PROCEDURE testproc IS BEGIN FOR i IN 1..3 LOOP INSERT INTO b_test VALUES (i); END LOOP; END; /

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 COL1 --------1 2 3 * b_test;

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C39

C40

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Summary
Manipulating PL/SQL Using SQL*Plus You can use SQL*Plus to create, debug, and execute PL/SQL blocks
D

Create and modify anonymous blocks and program units with SQL*Plus and the online editor. Execute SQL*Plus commands, anonymous blocks, program units, and SQL statements. Compile procedures and functions. Create and manipulate SQL*Plus variables for passing values in and out of your PL/SQL block. Embed messages to assist with debugging code.

D D

SQL and SQL*Plus Comparisons SQL and SQL*Plus are distinctively different languages, but are used together to create reports. SQL communicates with the Oracle7 Server to access data. The SQL commands are stored in the SQL buffer, and they are executed by a termination character. SQL*Plus commands recognize SQL commands and send them to the Oracle7 Server. SQL*Plus commands are entered one line at a time and are not stored in the SQL buffer. SQL*Plus Commands SQL*Plus commands are useful in developing reports that are based on a query. They can set up the environment at log in when they reside in the login.sql file.

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C41

C42

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice Overview
This practice will familiarize you with the SQL*Plus commands used to build reports and those used with PL/SQL blocks. Practice Contents
D D D D

Distinguishing between SQL and SQL*Plus Customizing reports Executing a PL/SQL anonymous block Creating and executing a stored function

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C43

C44

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice C
1.

Determine whether each of the following commands is a SQL or SQL*Plus command. Place a check in the appropriate column. Command DESCRIBE SPOOL SELECT SET RUN INSERT SQL SQL*Plus

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 Display the definition of a table. Suppress the message displaying the number of rows returned from a query. Control the character length of a line. Specify a heading to appear at the top of each report page. Alter the display characteristics of a column. Document a command or script file. Send output to a file for printing later. Command SET LINESIZE SPOOL DESCRIBE SET FEEDBACK OFF TTITLE COLUMN REM

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C45

Practice C
3.

continued

Load and execute a loop counter.


a. b. c. d. e. f.

Launch SQL*Plus. Your instructor will give you the login information. Start the LABS\pcloop.sql file to create the COUNT_LOOPS procedure. View the arguments for the COUNT_LOOPS procedure by using the DESCRIBE command. Create a global variable named G_OUTPUT to hold a text string from the argument V_OUTPUT. Execute the COUNT_LOOPS procedure. Display the value in the G_OUTPUT global variable.

4.

Execute an anonymous PL/SQL block that accepts a number and determines if it is odd or even.
a. b. c.

Start the LABS\pcmsg.sql file to execute the PL/SQL block. Enter a value at the prompt. Sample values are 3, hello, NULL, and 6 Display the value in the G_MESSAGE global variable.

C46

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice C Solutions
1.

Determine whether each of the following commands is a SQL or SQL*Plus command. Command DESCRIBE SPOOL SELECT SET RUN INSERT X X X X SQL SQL*Plus X 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 Display the definition of a table. Suppress the message displaying the number of rows returned from a query. Control the character length of a line. Specify a heading to appear at the top of each report page. Alter the display characteristics of a column. Document a command or script file. Send output to a file for printing later. Command SET LINESIZE SPOOL DESCRIBE SET FEEDBACK OFF TTITLE COLUMN REM

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C47

Practice C Solutions
3.

continued

Load and execute a loop counter.


a. b.

Launch SQL*Plus. Your instructor will give you the login information. 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 the DESCRIBE command.
SQL> DESCRIBE count_loops PROCEDURE count_loops Argument Name --------------------V_COUNT V_OUTPUT Type In/Out Default? ------------- ----- -------NUMBER IN VARCHAR2 OUT

d.

Create a global variable named G_OUTPUT to hold a text string from the argument 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

C48

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Practice C Solutions
4.

continued

Execute an anonymous PL/SQL block that accepts a number and determines if it is odd or even.
a. b. c.

Start the LABS\pcmsg.sql file to execute the PL/SQL block. Enter a value at the prompt. Sample values are 3, hello, NULL, and 6 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 number Enter a number: NULL null is not a valid number Enter a number: 6 PL/SQL procedure successfully completed. SQL> PRINT g_message G_message ------------------------------------------EVEN number

Using SQL*Plus to Create Reports and Manage PL/SQL Code

C49

C50

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

D
Related Products and Services

D2

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Related Products
DBA*Assist Version 1.4 is a SQL*Forms application that aids the DBA in managing the Oracle Version 6.0 database. Using a simple and effective menu structure, DBA*Assist provides a powerful productivity tool to simplify Oracle database administration in the key areas below. User Maintenance
D

Query, add, and alter database users and their attributes.

Space Analysis
D

Displays information screens on tablespace size, usage and fragmentation at the three distinct levels of tablespace, user and object.

Space Estimation
D

Define tables and indexes and perform what if analysis to estimate space and proper storage procedures.

Tablespace and Rollback Segment Maintenance


D

Query, add, drop, and alter tablespaces and rollback segments.

Client/Server
D

Invoke DBA*Assist as a client SQL*Forms application and manage the target database over a SQL*Net connection.

Related Products and Services

D3

D4

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Related Services
When you need to augment your internal resources, need specific technical expertise, or are seeking to maximize your technology investments fully, partnering with Oracle Services is the answer. No one is more qualified than the Oracle Services team of consultants to help you implement, customize, or integrate client-server technology. Our 3,500 consultants in 43 countries can help you with local projects or enterprise-wide, global, or multi-size implementations. We work closely with your in-house staff to ensure that the solutions are tailored to your needs, and to transfer the skills required to maintain and expand the completed system. Oracle Consulting
D

Business Process Reengineering (BPR) increases productivity by rapidly providing you with efficient, streamlined yet flexible processes and technology solutions that support your strategy. Custom Application Development draws upon our tools and CASE experience to deploy rapidly specialized, easytomaintain client-server applications for your business. Applications Consulting services offer experienced consultants who specialize in rapidly implementing Oracle Cooperative Applications. Oracle Industries develops integrated solutions for specific industries using a combination of Oracle and third-party products and services. Core Technology Services help you through support, system and applications audits, performance tuning, and technology upgrades. Open Systems Transformation services provide an architecture and implementation road map to transfer systems from legacy environments to client-server.

For more information on Oracle Services, please call 1800ORACLE1 or contact your local Oracle office.

Related Products and Services

D5

D6

Introduction to Oracle: SQL and PL/SQL Using Procedure Builder

Glossary A
actual parameter The variable or expression referenced in the parameter list of a subprogram call. Ada A high-level programming language developed by the U.S. Department of Defense for use in embedded computer systems. alias A temporary name assigned to a table, view, column, or value within a SQL statement, used to refer to that item later in the same statement or in associated SQL*Plus commands. anonymous block A PL/SQL program unit that has no name and does not require the explicit presence of the BEGIN and END keywords to enclose the executable statements. Since they are unnamed, anonymous blocks cannot be referenced by other program units. application One or more program modules used to achieve a specific result. Applications can be nested within other applications. For example, an application to control a companys inventory could consist of various Forms applications for input of data, and various Graphics applications to display the data visually. application subprogram A procedure or function that resides and executes in an application. argument 1. An expression within the parentheses of a subprogram, supplying a value for the subprogram to operate on. For example, in the expression MY_PROC(x), x is the argument. 2. Clauses containing keywords and their specified values. For example, PRINT=YES is an argument. ASCII Acronym for American National Standard Code for Information Interchange.

B
batch compile To translate, at once, several PL/SQL program units into a machine executable form. bind reference A reference to a parameter used to replace a single literal value (for example, a character string, number, or date) appearing anywhere in a PL/SQL construct or a SQL SELECT statement. For a bind reference, you must precede the parameter name with a colon (:). See also: lexical reference, parameter, global variable. bind variable A global variable you can create outside of a package in a standalone session of Procedure Builder. block The basic program unit in PL/SQL, defined by the keywords DECLARE, BEGIN, EXCEPTION, and END. body Contains the same information as the program unit specification, and also includes the actual implementation of the subprogram (that is, its sequence of actions). In most cases, only a body must be defined for a subprogram. breakpoint A debug action you can place at any source in a PL/SQL

Glossary1

subprogram that interrupts execution of the program unit and passes control to the PL/SQL Interpreter. Breakpoints allow you to incrementally execute a subprogram. built-ins A collection of extensions to the PL/SQL language that are designed to be used with Developer/2000. Built-ins include datatypes, procedures, functions, exceptions, and constants. buffer A temporary storage area for data during the transfer of that data between the computer and a peripheral, or between parts of a computer. A buffer prevents loss of information due to differences in the speed or timing of the transfer and speeds up certain functions.

resulting Cartesian product will be 10,000 rows. CHAR datatype An Oracle datatype provided for ANSI/ISO compatibility. A CHAR column is a fixed-length column and can contain any printable characters, such as A, 3, &, or blanks, and can have from 1 to 255 characters or can be null. child An object that is a member of a group, and is immediately below that group object in its group tree. The objects that compose a group object are children of that group. Every object is a child of its parent. clause A part of a SQL statement that does not constitute the full statement; for example, a WHERE clause. client A user, software application, or computer that requests the services, data, or processing of another application or computer (the server). In a two-task environment, the client is the user process. In a network environment, the client is the local user process and the server may be local or remote. client-server architecture Separation of processing between two CPUs, one acting as the server that provides services in a transaction and the other as the client in the transaction, requesting and receiving services. All responsibilities of shared data management can be processed by the computer running the database management system while the workstations running the database application concentrate on the interpretation and display of data. Clipboard A memory buffer. An object remains on the Clipboard until you

C
call stack A chain of subprogram calls, from the initial entry point down to the currently executing subprogram. Each subprogram call is represented by a frame on the downward-growing call stack, in which newly entered subprograms are added to the bottom of the stack. Cartesian product When you deactivate a relationship that is the only path relating two data sources, then execute a query using fields from both sides of the relationship, the result is a Cartesian product. The query combines all rows from all included data sources. A Cartesian product always retrieves many rows and information that is seldom useful. For example, if two data sources each contain 100 rows, the

Glossary2

cut or copy another object, or until you quit the application. column A vertical space in a database table that represents a particular domain of data. A column has a column name (for example, ENAME) and a specific datatype (for example, CHAR). For example, in a table of employee information, all of the employees names would constitute one column. A record group column represents a database column. command line An operating-system command line. Most Oracle products can be invoked from a command line using a number of executable arguments. commit To make changes to data (inserts, updates, deletes) in the database permanent. Before changes are stored, both the old and new data exist so that changes can be stored or the data can be restored to its prior state. compile To translate a source program as into a binary, executable format. PL/SQL program units must be compiled before they can be executed. composite datatype Datatype composed of multiple components. condition An expression whose value is either true or false, such as X> 100. For example, you can set a condition in a query when you want the query to display only those rows that evaluate as true in your expression. connect To log on to a database. You must connect if you want to create or

modify queries or access an application stored in a database. connect string The set of parameters, including a protocol, that SQL*Net uses to connect to a specific Oracle instance on the network. constraint A rule or restriction concerning a piece of data (such as a NOT NULL restriction on a column) that is enforced at the database level, rather than the object or application level. construct A PL/SQL code structure. There are two types of constructs: non-value constructs do not return a value; value constructs return a value. control structures Programming structures related to decision-making: selection, iteration, and sequence. copy To store a replica of a selected object on the Clipboard, so that it may be pasted elsewhere in an editor if desired. Cue Cards Just-in-time coaching for frequently performed tasks. Available in Oracle Procedure Builder. cursor 1. A small icon representing the position of the mouse. The shape of the cursor varies, depending on the selected tool. 2. An internal pointer to data retrieved by a query. A cursor points only to one row of data at a time; however, you can use built-in subprograms to move the cursor to any row in the data set. cut To delete one or more objects and store them in the Clipboard, so that they may be pasted elsewhere in an editor, if desired.

Glossary3

D
data control language (DCL) The category of SQL statements that control access to the data and to the database. Examples are the GRANT and REVOKE statements. Occasionally DCL statements are grouped with DML statements. data definition language (DDL) The category of SQL statements that define or delete database objects such as tables or views. Examples are the CREATE, ALTER, and DROP statements. data dictionary A set of tables and views owned by the database administrator. It is a central source of information for Oracle Server and other relational databases. data manipulation language (DML) The category of SQL statements that query and update the database data. Common DML statements are SELECT, INSERT, UPDATE, and DELETE. Occasionally DCL statements are grouped with DML statements. data model A relational model that defines what data should be fetched from the database, what values should be computed, and how data should be ordered in a report. Reports objects that define the data model are queries, groups, columns, parameters, and links. database A set of dictionary tables and user tables that are treated as a unit. datatype A standard form of data. The Oracle datatypes are CHAR, DATE,

NUMBER, LONG, RAW, and LONG RAW. DATE An Oracle Server datatype. A date column may contain a date and time between January 1, 4712 B.C. and December 31, 4712 A.D. debug To detect, diagnose, and eliminate errors in programs. debug action An user specified event placed in a PL/SQL subprogram using Procedure Builder functionality, usually for the purpose of troubleshooting errors raised during subprogram execution. See also: breakpoint, debug trigger. debug trigger A conditional debug action you can place at any source line in a PL/SQL subprogram. If the specified condition is met, the specified action is taken before execution of the subprogram resumes. debugger The Procedure Builder functionality within another Developer/2000 component that simulates runtime execution of an application for testing and debugging. default A value supplied by the system when a user does not specify a required command parameter or attribute. descendant An object that appears in another objects group tree at any position below that other object. Every object is a descendant of its antecedents. drag Press and hold down a mouse button while you slide the mouse pointer to a particular location in a window. duplicate An option that allows you to copy objects directly on the layout

Glossary4

without affecting the contents of the Clipboard. See also: copy.

foreign key A value or column in one table that refers to a primary key in another table. formal parameter The variable declared in a subprogram specification and referenced in the subprogram body. function A PL/SQL subprogram that executes an operation and returns a value at the completion of the operation. A function can be either built-in or user-named. Contrast with procedure.

E
editor A work area in which you perform a specific set of tasks, such as creating a program unit or designing an application. equijoin A type of join where the join condition is an equality, such as WHERE S_EMP.DEPT_ID = S_DEPT.ID. exception A warming or error condition generated from a PL/SQL subprogram. executable argument An argument you can pass to a product executable, such as OPENFILE=my_disp and PRINT=YES. These arguments usually are specified when the executable is invoked from a command line. export To store a copy of a module to a file or database. expression A PL/SQL construct combining variables, constants, literals, and operations on their values. external PL/SQL library See library. external query An ANSI-standard SQL SELECT statement that can be referenced by other Oracle products.

G
global variable A logical container that exists across an application. When an application uses a global variable, the application maintains the variable until the application is exited, or until another object explicitly removes it. See also: parameter, bind variable, local variable grant To give a user access to a module. Only a modules creator can grant its access to other users. group function A SQL function that computes a single summary value from the individual values in specified groups of rows. Examples are AVG, MAX, or SUM. GUI Acronym for Graphical User Interface. Also known as a bitmapped interface.

F
field The data stored at the intersection of a row and a column.

H
heading node A node in the Object Navigator denoting a type of object which can be contained within or

Glossary5

associated with a report. Selecting a heading node does not select an object in the report. host variable See global variable.

J
join Combining data from two (or more) tables in a single SELECT statement.

K I
icon A graphic representation of a window or tool. identifier See name. keyword Part of a command line syntax that must be supplied with a corresponding argument.

L
lexical reference A reference to a parameter used to represent a string of text in a SQL SELECT statement. For a lexical reference, you must precede the parameter name with an ampersand (&). See also: bind reference, parameter library A collection of one or more PL/SQL program units that are stored together in a file or database, and that can be referenced by several applications at once. local database 1. The database on the computer running the application. 2. The database to which an application is connected. This database parses and executes all SQL statements generated by the application. See also: NO TAGremote database. local variable A PL/SQL variable declared only within the scope of the current program unit. See also: parameter, bind variable, global variable. LONG datatype A standard ORACLE datatype. A LONG column may contain any printable character, such as A, 3, &,

IF statement Control structure that allows you to execute a sequence of statements conditionally. import To read a module from the file system or database, and incorporate it into an application. index An optional structure associated with a table that is used by Oracle Server to locate rows of the table quickly, and (optionally) to guarantee that every row is unique. insert mode A mode in which each character you enter is inserted at the cursor, pushing the following characters to the right. The opposite of Replace mode. Interpreter Define, display, debug, and execute Pl/SQL program units in the Interpreter window of Oracle Procedure Builder. Interpreter script A file containing any mixture of PL/SQL source, Procedure Builder commands, and SQL statements.

Glossary6

or blanks, and can be any length from 1 to 65K characters; alternatively it can be null. loop In a PL/SQL subprogram, a conditional statement that is repeated until the condition is no longer met.

O
Object Navigator The window containing a hierarchical list of objects for the current session. The list appears in outline form, and enables the user to accomplish several tasks such as creating, editing, renaming, and deleting objects. object privileges Privileges granted (assigned) to end users so that they can use a database application to accomplish specific tasks. Object privileges perform a particular action on a specific object. For example, the privilege to delete rows of a specific table is an object privilege. outer join A type of join that returns rows from one table that do not satisfy the join condition, in addition to those that do satisfy the condition. Each additional row is joined to an imaginary row in the other table in which all the fields are null.

M
megabyte (Mb) A unit of memory equal to 1,048,576 bytes (1024 x 1024). Often rounded to one million bytes. module An object that can be shared by multiple applications. External queries and PL/SQL libraries are examples of modules.

N
name The unique identifier given to an object. node A specific location in the Object Navigator object hierarchy. Nodes can be expanded to reveal information about an object, such as cross references to other objects. NULL value The absence of a value.

P
packaged function A PL/SQL function provided with Developer/2000 that can be referenced anywhere within a program unit. package A method of encapsulating and storing related procedures, functions, variables, and other package constructs together as a unit in the database. While packages provide the database administrator or application developer organizational benefits, they also offer increased functionality and database performance. package body Includes the actual implementation of the package, which may include private subprograms and

Number datatype A standard ORACLE datatype. A NUMBER column can contain a number, with or without a decimal point and a sign, and can have from 1 to 105 decimal digits (only 38 digits are significant).

Glossary7

datatypes. The body is optional if the package consists only of declarations. package specification Declares the public interface to the packagethat is, the datatypes and subprograms that can be referenced by other program units. pane A distinct portion of an editor where work is performed, usually resizeable. parameter A global variable that is defined in an application and exists outside of a PL/SQL package or subprogram. See also: bind reference, lexical reference. parameter list A named programmatic construct that lists parameter names (called keys), their types, and their values. parent An object that is immediately above another object in its group tree. A group object is the parent to each of the objects that compose it. Every object is the parent of its children. paste To place the contents of the Clipboard (cut or copied objects) on the layout. PL/SQL A procedural extension of SQL that provides programming constructs such as conditionals and procedures. .pld The standard extension given to the file representation of a Procedure Builder Interpreter script. .pll The standard extension given to the file representation of a PL/SQL library.

.pls The standard extension given to a PL/SQL program unit that has been exported to a text file. primary key In a database table, a set of columns used to enforce uniqueness of rows. The combination of column values is unique for each row in the table. The primary key is the most frequently used means of accessing rows. privilege A right to successfully execute a particular type of SQL statement. Some examples of privileges include rights to connect to the database (create a session), to create a table in your schema, to select rows from someone elses table, and to execute someone elses stored procedure. The privileges of an Oracle database can be divided into two distinct categories: system privileges and object privileges. procedure A PL/SQL subprogram that performs a specified sequence of actions. program unit A code structure you can create using PL/SQL. Anonymous blocks, subprogram specifications and bodies, and package specifications and bodies are examples of program units. See also: subprogram protocol A string you can enter when connecting to a database or server that allows you to connect to a remote database or server. pull-down menu A set of options, displayed horizontally under the application window title. Each option can represent a submenu or an action.

Q
query A SQL SELECT statement that specifies the data you wish to retrieve

Glossary8

from one or more tables or views of a database. Quick Tour Online help used to introduce you to product terminology, workflow, and theoretical concepts. Available in Oracle Procedure Builder. quit An option that terminates the current session and returns the user to the operating system. On some systems, Quit is Exit.

row One set of field values in a table; for example, the fields representing one employee in the example table S_EMP.

S
schema A collection of related objects. Schema objects includes tables, views, sequences, stored program units, synonyms, indexes, clusters, and database links. scope The level at, or range in which, an object operates.

R
RDBMS (Relational Database Management System) An Oracle Version 6 (and earlier) term. Refers to the software used to create and maintain the system, as well as the actual data stored in the database. record One row fetched by a SELECT statement. relational operator A symbol used in search criteria to indicate a comparison between two values, such as the equal sign in WHERE DEPTNO = 10. Rows in which the comparison results in TRUE are returned in the result (fetched), while rows in which the comparison returns FALSE are rejected from the result. replace mode A mode in which each character you enter replaces the current character at the cursor. The opposite of insert mode. roles Named groups of related privileges that are granted to users or other roles.

script See SQL script, Interpreter script SELECT statement A SQL statement that specifies which rows and columns to fetch from one or more tables or views. See also: SQL statement, query sequence A database structure used to generate unique integers to be used as primary keys (which are guaranteed to be unique). Concurrent database users can use a sequence simultaneously. Sequences may be defined with many characteristics (for example, to ascend or descend, have any increment or decrement, and to recycle values or not). session The period between invoking and quitting the executable. source PL/SQL statements provided in a subprogram or package. You must have the source code for a program unit before you can compile it into executable form. specification Defines only the names, parameters, and return type (applies to functions only) of the subprogram. split bar A small rectangle at the bottom of the vertical scroll bar and to the left of

Glossary9

the horizontal scroll bar in an editor. Dragging and releasing the mouse button creates a pane, creates a new split bar at that location, and divides the scroll bar into separate scroll bars for each pane. See also: pane, scroll bar. SQL Standard interface for storing and retrieving information in a relational database. SQL is an acronym for Structured Query Language. SQL buffer In SQL*Plus, the default buffer used to contain the SQL command or PL/SQL block most recently entered. SQL*Plus An interactive SQL-based language for data manipulation, data definition and the definition of access rights for an Oracle database. Often used as an end-user reporting tool. SQL script A file containing SQL statements that you can run to perform database administration quickly and easily. Several SQL scripts are shipped with Oracle products. SQL statement A SQL instruction to Oracle. A SELECT statement is one type of SQL statement. See also: SELECT statement, query stack See call stack.

stored subprogram A procedure or function that resides and executes in the Oracle7 Server. Procedure Builder can call stored subprograms. subprogram A PL/SQL procedure or function. See also: program unit subquery A query that is nested in a clause of a SQL command. substitution parameter A two-character variable of type CHAR that is referenced in a menu item command 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 is not actually an object itself, it is a direct reference to its base object. Synonyms are used to mask the real name and owner of an object, provide public access to an object, provide location transparency for tables, views, or program units of a remote database, and simplify the SQL statements for database users. A synonym can be public or private. syntax The orderly system by which commands, qualifiers, and parameters are combined to form valid command strings.

statement A PL/SQL construct used for conditional, iterative, and sequential control, and for error handling. A semi-colon (;) must terminate every PL/SQL statement. stored program unit A procedure, function, or package that resides and executes in the Oracle7 Server.

T
table A named collection of related information, stored in a relational database or server, in a two-dimensional grid that is made up of rows and columns. toggle A setting that can be turned either on or off. For example, you can hide or show the Object Navigator.

Glossary10

tool An icon that appears in the Layout editor or Object Navigator. Tools are used to create and manipulate objects in an application. toolbar Collection of iconic buttons that perform product commands. Usually aligned horizontally along the top, or vertically down the side of a window. transaction A sequence of SQL statements treated as a single unit. trigger A PL/SQL procedure that is executed, or fired, at upon a specific event.

(alphanumeric) data. In Oracle RDBMS V6, CHAR and VARCHAR are equivalent. In Oracle7, CHAR data is fixed-length and VARCHAR is variable-length. variable A named object that can be assigned a value and whose assigned value may change over time. See also: parameter, bind variable, global variable, local variable view A virtual table whose rows do not actually exist in the database, but which is based on a table that is physically stored in the database.

U
update To change the values for table data, in particular, by altering data values using the SQL command UPDATE, but also by deleting values using the SQL command DELETE or by inserting values using the command INSERT. user-named parameter A type of substitution parameter that is created in the Forms designer (valid for a given menu module).

W
wildcard A character used to mean any one character or a contiguous set of characters within a word or phase. window A rectangular area of the desktop that contains an application. Each window has an area where you can interact with the application. Windows can be opened, resized, moved, reduced to an icon, or enlarged to fill the entire desktop.

V
VARCHAR2 datatype Equivalent to the CHAR datatype, a standard Oracle datatype used to store character

XYZ
zoom To expand an object to allow more room for editing the contents of the field.

Glossary11

Glossary12

Index
Symbols
;. See semicolon :. See colon :=. See assignment operator ". See quotation marks `'. See quotation marks (+). See outer join operator &. See ampersand #. See unique identifier -. See dash *. See asterisk ||. See concatenation operator application partitioning, 1911 argument, 2011 IN, 2013, 2219 arithmetic expressions, 113 arithmetic operators, 113, 325 ASC, 25 assignment operator, 217, 2129, 2221 asterisk (*), 19, 833 attribute, 815 %FOUND, 2417 %ISOPEN, 2417, 2419 %NOTFOUND, 2417 %ROWCOUNT, 2417, 2419 %ROWTYPE, 2123 %TYPE, 2113, 229 cursor, 2425 definition, 813 explicit cursor, 2417

A
ACCEPT command, 715, 1117 active set, 2411, 2413, 2415 alias column, 121, 27, 1411 table, 413 ALTER SEQUENCE command, 1317 ALTER TABLE command, 127 ADD clause, 127 add columns, 127 ADD constraint clause, 1211 DEFAULT keyword, 127 DISABLE clause, 1215 DROP constraint clause, 1211 ENABLE clause, 1215 MODIFY clause, 129 modify columns, 129 NOT NULL constraint, 127 ALTER USER command, password, 1613 alternate key, 825 ampersand (&), 79, 1117, 2021 single, 79 anonymous block, 1811, 1813

B
B*Tree. See index BINARY_INTEGER, 2115 block, 189 Boolean condition, 237, 2313 breakpoint, 1937, 1939, 1941 setting, 1937 BTITLE command, C17 built-in package, 1919 button Go, 1939 reset, 1939 Step Into, 1939 Step Out, 1939 Step Over, 1939 Vertical Button Bar, 1921

C
Call Stack, 1943 candidate key, 825 Cartesian Product, 47 character function, 39 character pattern matching, 221 CHECK constraint, 823, 915, 923 code breakpoint, 1941 commenting, 2143 conventions, 2145 debugging, 1937, 2143, 2511 naming, 2145 stepping through, 1939 testing, 1937, 1943 colon (:), 2141 column, I11 column alias, 121, 27, 1411 See also column heading COLUMN command, 145 format model elements, 149 column constraint, 917 CHECK, 923 FOREIGN KEY, 921 NOT NULL, 919 PRIMARY KEY, 921 UNIQUE, 919 column heading, 111 command file, C15 comment, 2143 delimiter, 2125 COMMENT command, 1221 COMMIT command, 2427 COMMIT statement, 1137, 1141, 2227 comparison operator. See operator compile, 1931, 207 steps, 1929 composite primary key, 825 compound primary key, 825

concatenation operator, 123 condition, 2325 conditional construct. See IF statement CONSTANT keyword, 217 constraint. See CHECK constraint; FOREIGN KEY constraint; NOT NULL constraint; PRIMARY KEY constraint; UNIQUE constraint constraints, 915 column, 917 data integrity, 823 column, 823 entity, 823 referential, 823 user-defined, 823 table, 917 control structure, 185, 235 IF statement, syntax, 237 loop, 2317 conversion function, 333 COUNT function, 511 CREATE FUNCTION command, 207 RETURN statement, 2017 CREATE INDEX command, 1513 CREATE PROCEDURE command, 207 CREATE SEQUENCE command, 137 CREATE SYNONYM command, 1625 CREATE TABLE command, 97, 925 subquery, 931 CREATE USER command, 167 CREATE VIEW command, 147 WITH CHECK OPTION clause, 1417 WITH READ ONLY option, 1419 Cue Cards, 1913 CURRVAL, 99, 1313 cursor, 2223, 245 attribute, 2425 explicit, 227, 2215, 245, 247, 2421 attributes, 2417 closing, 2415 CURSOR statement, 249

declaring, 249 FETCH statement, 2413 fetching, syntax, 2413 FOR UPDATE clause, 2427 opening, 2411, 2423 WHERE CURRENT OF clause, 2427 FOR loop, 2425 implicit, 2223, 245 cursor FOR loop. See cursor CURSOR statement. See cursor

data manipulation language (DML), I25, 115, 1135, 225, 2223 DELETE statement, 1129 INSERT command, 117 UPDATE statement, 1121 view, 1415, 1419 database, I9 database design, 85 table instance chart, 829 database security, 165 Database Trigger editor, 195, 199 datatype, 913, 219 BINARY_INTEGER, 2115 composite, 2115 conversion, 2139 parameter, 2423 scalar, 219 date format elements, 337 date function, 327 DBMS_SQL package, 225 DCL. See data control language DDL. See data definition language debug action, 1933, 1935, 1937 declarative section, 189, 215 DEFAULT keyword, 97, 99, 127, 217 default value, 2219 DEFINE command, 715 DELETE statement, 1129, 2219 DESC, 25 DESCRIBE command, 139, 933, 1013 DISTINCT keyword, 131 DML. See data definition language DROP INDEX command, 1519 DROP SEQUENCE command, 1319 DROP SYNONYM command, 1627 DROP TABLE command, 1217 CASCADE CONSTRAINTS option, 1217 DROP VIEW command, 1423

D
dash (-), 1117 data control language (DCL), I25, 97, 1135, 225 ALTER USER command, 1613 CREATE ROLE command, 1611 CREATE SYNONYM command, 1625 CREATE USER command, 167 DROP SYNONYM command, 1627 GRANT command, 1615 REVOKE command, 1623 data definition language (DDL), I25, 97, 1135, 1925 ALTER TABLE command, 125 COMMENT command, 125 CREATE TABLE command, 97 DROP TABLE command, 1217 RENAME command, 125 TRUNCATE command, 125 data dictionary, 917, 933, 105 DICT_COLUMNS, 109 DICTIONARY, 109 privileges, 1621 USER_CONS_COLUMNS, 1015, 1213 USER_CONSTRAINTS, 1013, 1213 USER_IND_COLUMNS, 1517 USER_INDEXES, 1517 USER_OBJECTS, 109, 1311 USER_SEQUENCES, 1311 USER_VIEWS, 1421 data integrity constraints, I15, 823

DUAL table, 323

footer. See BTITLE command FOR UPDATE clause, 2427 foreign key, I11, 827, 837 FOREIGN KEY constraint, 823, 915, 921, 931 ON DELETE CASCADE, 923 function, 35, 1813, 205, 2223 character, 39 CONCAT, 39 INITCAP , 39 LENGTH, 39 LOWER, 39 NVL, 39 SUBSTR, 39 UPPER, 39 conversion, 333 See also date format elements TO_CHAR, 333, 335, 345 TO_DATE, 333, 349 TO_NUMBER, 333, 349 date, 327 ADD_MONTHS, 327 LAST_DAY, 327 MONTHS_BETWEEN, 327 NEXT_DAY, 327 ROUND, 327 TRUNC, 327 group, 55 AVG, 57 COUNT, 57 MAX, 57 MIN, 57 STDDEV, 57 SUM, 57 VARIANCE, 57 in SQL statements, 2025 invoking, 2025 multiple row, 35 nesting, 351 number, 317 MOD, 317 ROUND, 317 TRUNC, 317 NVL, 129 single row, 35, 37 SQL, 2015 SQLCODE, 2519

E
empty string (`'), 119 entity, 815 definition, 813 entity relationship model, 813, 829 attribute, 813 entity, 813 normalization, 821 relationship, 813 equijoin, 411 error handling. See exception-handling section exception, 189, 2213, 2215, 2411, 255 INVALID_CURSOR, 2415, 2511 NO_DATA_FOUND, 2215, 2217, 255, 2511 non-predefined Oracle7 Server error, 257, 2515 predefined Oracle7 Server error, 257, 2511 propagating, 255, 2521 RAISE statement, 255, 2517 SQLCODE, 2519 SQLERRM, 2519 TOO_MANY_ROWS, 2215, 2217, 2511 trapping, 255 syntax, 259 user-defined, 257, 2517 WHEN OTHERS clause, 259, 2519 exception-handling section, 189, 205, 215, 255, 259 executable section, 189, 215, 255 EXECUTE command, 2021 EXIT statement. See loop export, program unit, 1929

F
FETCH statement. See cursor field, I11

SQLERRM, 2519 standalone, 2023 syntax, 2017 SYSDATE, 323, 325 TO_DATE, 1113 user-defined, 2015

DROP INDEX command, 1519 guidelines, 1515 non-unique, 1511 optimization, 157 ROWID, 159 single column, 1511 UNIQUE, 919, 921, 1511 INSERT statement, 117, 2219 subquery, 1119 integration, 187 Interpreter, 199, 1923 Interpreter pane, 1923, 1925 INTO clause, 227, 229, 249, 2413 INVALID_CURSOR exception, 2415

G
Go button, 1939 GRANT command, 169 object privileges, 1615 PUBLIC keyword, 1619 WITH GRANT OPTION clause, 1619 GRANT ROLE command, 1611 GROUP BY clause, 513, 519, 523 group function, 55 subquery, 613

J
join Cartesian Product, 47 equijoin, 411 non-equijoin, 419 outer, 421 self join, 425 simple, 49 table alias, 417 table prefix, 413 WHERE clause, 49 join condition, 45

H
HAVING clause, 521, 525 group function, 525 header. See TTITLE command help Cue Cards, 1913 online, 199 Quick Tour, 1911

I
identifier, 185, 2023, 217, 2125, 229, 2221, 255 IF statement, 235 nested, 2311 syntax. See control structure IN mode, 2011 IN OUT mode, 2011, 2019 index, 155 B*Tree, 155, 159 concatenated, 1511 CREATE INDEX command, 1513

L
lexical unit, 2125 library, 1919, 1921 attached, 1919 LIKE operator, 221 literal, 125, 2125 logical condition, 2313 login.sql file, 719, C11 loop, 2317 basic, 235 syntax, 2317 cursor FOR, 2425

EXIT statement, 235, 2317 FOR, 235 syntax, 2321 labels, 2327 nested, 2327 WHILE, 235 syntax, 2325 with cursors, 2417, 2419 looping constructs, 235

O
Object Navigator, 195, 199, 1915, 1927, 1937 ON DELETE CASCADE. See FOREIGN KEY constraint OPEN cursor. See cursor operator, 2135 AND, 227 BETWEEN, 219 comparison, 211, 215 IN, 219 IS NULL, 225 LIKE, 221 %, 221 _, 221 ESCAPE option, 223 logical, 215, 2313 OR, 227 SQL, 215 operator precedence, 117 Oracle7 Server, I19 ORDER BY clause, 25 See also SELECT statement OUT mode, 2011, 2019 outer join, 421 outer join operator ((+)), 421

M
mode IN, 2011 IN OUT, 2011 OUT, 2011 model. See entity relationship model modularity, 185 multiple row subquery, 617

N
naming guidelines, 911 naming rules, 911 nested block, 2127 nesting functions. See function NEXTVAL, 99, 1313 NO_DATA_FOUND exception. See exception node, 1921 normalization, 821 NOT NULL constraint, 127, 825, 833, 915, 919, 931, 933, 127 NOT NULL keyword, 217, 2113 NULL keyword, 119 null value, I11, 127, 225, 827, 217 number function, 317 NVL function, 129

P
package, 1811, 205 parameter, 721, 2423, 2425 actual, 2011, 2021 formal, 2011 local, 1943 modes, 2011 substitution, 2021 syntax, 209 password, 1613 PL/SQL, I19, I23, 185, 1815 PL/SQL block, nesting, 2127 PL/SQL Interpreter. See Interpreter

PL/SQL record, 2119, 227, 2211, 2421, 2425 declaring, 2121 syntax, 2121 PL/SQL table, 2115 declaring, 2117 syntax, 2117 portability, 187 pragma EXCEPTION_INIT, 2515 precedence, 229 primary key, I11, 825, 827 PRIMARY KEY constraint, 127, 823, 915, 921, 1215 index, 155 PRIMARY KEY index, 1215 privilege, 97, 105, 165 object, 165 system, 165 procedure, 1813, 205 syntax, 209 Procedure Builder, 1817, 195, 207, 2227, 2511, 2521 program construct, 1811 program unit, 195, 1919, 1929, 205 Program Unit editor, 195, 199, 1927 pseudocolumn CURRVAL, 923 LEVEL, 923 NEXTVAL, 923 ROWNUM, 923 PUBLIC keyword, 1619

R
RAISE statement. See exception recursive relationship, 817, 819 referential integrity constraint. See FOREIGN KEY constraint relational database, I9 relationship, 817 definition, 813 many-to-many, 819 many-to-one, 819, 837 one-to-one, 819, 837 recursive, 817 RENAME command, 1219 Reset button, 1939 RETURN statement, 2017 REVOKE command, 1623 role, 165, 1611 ROLLBACK statement, 1137, 1143, 2227 row, I11 ROWID, 159, 2421, 2427

S
SAVEPOINT statement, 1137, 1145, 2229 schema, 99 scope, 2127 script file, 721, 925, C15, C19 search, 1921 security, 165 role, 165 SELECT command. See SELECT statement SELECT statement, 1111, 245 basic query, 15 FROM clause, 19 GROUP BY clause, 513 guidelines, 17 HAVING clause, 525 INTO clause, 227 ORDER BY clause, 25

Q
Quick Tour, 1911 quotation marks double, 121, 2125 single, 125, 213, 711, 717, 117, 1115, 2125, 2131

outer join, 421 rules, 17 SELECT clause, 19, 229 simple join, 49 syntax, 227 WHERE clause, 211 self join, 425 semicolon (;), 227 sequence, 2013, 2219 ALTER SEQUENCE command, 1317 cache, 1315 CREATE SEQUENCE command, 137 DROP SEQUENCE command, 1319 gaps, 1315 SET command, C11 SET VERIFY command, 79 simple join, 49 sort order. See ORDER BY clause Source pane, 1923 SQL, 185, C9 SQL buffer, 17, 141 SQL command, I13, I23, 135 SQL cursor attributes, 2223 SQL%FOUND, 2223 SQL%ISOPEN, 2223 SQL%NOTFOUND, 2223 SQL%ROWCOUNT, 2223 SQL function, 2015, 2137 conversion, 2139 SYSDATE, 323, 325, 2013, 2219 USER, 2013, 2219 SQL statement, 225 SQL*Plus, I23, 135, 207, 2021, 2521, C9 editing commands, 141 file commands, 143 format commands, C15 parameter, 721 SET command, C11 SQLCODE function, 2519 SQLERRM function, 2519

stack, 1919 Stack node, 1911, 1943 statement level rollback, 1147 Step Into button, 1939 Step Out button, 1939 Step Over button, 1939 stored function, 1811 stored procedure, 1811 stored program unit, 1933 Stored Program Unit editor, 195, 199, 1931 stored subprograms, 205 subprogram, 1813, 197 See also function; procedure application, 205 creating, 207 invoking, 2021 subquery, 147 CREATE TABLE, 931 HAVING clause, 619 INSERT statement, 1119 multiple row, 617 single row, 611 UPDATE statement, 1121 WHERE clause, 619 substitution variable, 1115 syntax, rules, 2125 SYSDATE, 99, 923, 1111 See also SQL function system development cycle, I17, 87 system privilege, 167

T
table, I11, 15 ALTER TABLE command, 125 CREATE SYNONYM command, 1625 CREATE TABLE command, 97 DROP TABLE command, 1217 properties, I13 table alias, 417

table constraint, 917 CHECK, 923 FOREIGN KEY, 921 PRIMARY KEY, 921 UNIQUE, 919 table instance chart, 829, 833, 925 table prefix, 413 tables, 95 TEXT_IO package, 2023 TO_CHAR, 335, 345 TO_DATE, 349 TO_DATE function, 1113 TO_NUMBER, 349 TOO_MANY_ROWS exception. See exception transaction, 115, 1135, 2427 transaction control, 2227 TRUNCATE TABLE command, 1219 TTITLE command, C17

V
variable, 215, 249 bind, 2021 host, 2141, 2423 input, 2411 local, 1943 scalar, 219 Vertical Button Bar, 1921 view, 145 complex, 149, 1413 CREATE VIEW command, 147 DROP VIEW command, 1423 simple, 149

W
WHEN OTHERS clause. See exception WHERE clause, 211, 521, 227, 2213, 2221 See also join DELETE statement, 1129 UPDATE statement, 1125 WHERE CURRENT OF clause, 2427 wildcard search, 221

U
UID, 923 See also unique identifier UNDEFINE command, 719 UNIQUE constraint, 825, 915, 919, 1215 index, 155 unique identifier, 815, 819, 835 number symbol (#), 815, 835 UNIQUE index, 919, 921, 1215 unique key, 825, 827 UPDATE statement, 1121, 2219, 2221 USER, 99, 923 USERENV, 923 USERID, 1111

Das könnte Ihnen auch gefallen