Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
2,05 MB
Nội dung
Answers 627
2. What function do I use to combine two strings together?
You use the
CONCAT function; however, you can still rely on || to concatenate
strings.
3. What function converts
‘11/28/99’ to an Oracle DATE?
The
TO_DATE function gives you this flexibility.
4. You can use the
TRUNC and ROUND functions with what data types?
Both
NUMBER and DATE include the ROUND and TRUNC functions.
Exercises
1. Create a PL/SQL block that reads in the month of a date and displays the month in
a Roman numeral format. Use a date of 06/11/67. This allows you to practice the
TO_CHAR function. When printing the Roman numeral equivalent, use LTRIM to
remove any spaces padded to the left of the Roman numeral. If you are really
ambitious, on your own you can create the same RM-type function by using
IF THEN ELSE statements for practice from Day 4. Remember, practice helps
to solidify your knowledge through repetition and understanding.
Here is one solution:
DECLARE
v_Hold_Month Number;
BEGIN
v_Hold_Month := TO_NUMBER(TO_CHAR(TO_DATE(‘11-JUN-67’),’MM’));
DBMS_OUTPUT.PUT_LINE(v_Hold_Month);
DBMS_OUTPUT.PUT_LINE(‘Converted to Roman Numeral ‘ ||
LTRIM(TO_CHAR(v_Hold_Month,’RM’),’ ‘));
END;
/
Your output is
6
Converted to Roman Numeral VI
2. Use the TRUNC function on the SYSDATE to round to the nearest century.
The answer is
SELECT TO_CHAR(TRUNC(SYSDATE,’CC’),’MM/DD/YYYY HH:MI:SS AM’)
“Today’s Date and Time”
from DUAL
The output is similar to
Today’s Date and Time
01/01/1900 12:00:00 AM
A
29 7982 App 11.8.00 11:24 AM Page 627
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
3. Use CONCAT to link two strings together. Repeat the same line by using || instead
of CONCAT.
Here is one solution:
DECLARE
v_String1 VARCHAR2(60) := CONCAT(‘Connect String1 to’,
‘ String2’);
v_String2 VARCHAR2(60) := ‘Connect String1 to’ || ‘ String2’;
BEGIN
DBMS_OUTPUT.PUT_LINE(v_String1);
DBMS_OUTPUT.PUT_LINE(v_String2);
END;
/
Your output looks similar to
Connect String1 to String2
Connect String1 to String2
4. Calculate the number of days between 01/01/97 to 03/31/97. Remember to use the
TRUNC function to eliminate the TIME dependency.
The answer is
SELECT TRUNC(TO_DATE(‘03/31/97’,’MM/DD/YY’)) -
TRUNC(TO_DATE(‘01/01/97’,’MM/DD/YY’)) “Days_Subtracted”
from DUAL;
Your output is
Days_Subtracted
89
5. Convert the CHARACTER string ‘06/11/67’ to a date, and subtract from 06/11/97 to
see how old your author is (and holding).
The answer is
SELECT (TO_DATE(‘06/11/97’,’MM/DD/YY’) -
TO_DATE(‘06/11/67’,’MM/DD/YY’))/365 “Years Old”
from DUAL;
Your output is
Years Old
30.021918
6. Calculate how many months are between 05/15/97 and 08/22/97.
The answer is
628 Appendix
29 7982 App 11.8.00 11:24 AM Page 628
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Answers 629
SELECT MONTHS_BETWEEN(‘22-AUG-97’,’15-MAY-97’) “Fractional”
from DUAL;
Your output is
Fractional
3.2258065
7. Round the SYSDATE to the nearest century.
The answer is
SELECT TO_CHAR(ROUND(SYSDATE,’CC’),’MM/DD/YYYY HH:MI:SS AM’)
“Today’s Date and Time”
from DUAL;
Your output is similar to
Today’s Date and Time
01/01/2000 12:00:00 AM
8. Calculate the time in Newfoundland from Central Standard Time from 02-22-97,
05:00 AM.
Here is one solution:
SELECT TO_CHAR(NEW_TIME(TO_DATE(‘02-22-97 05:00:00 AM’,
‘MM-DD-YY HH:MI:SS AM’),
‘CST’,’NST’), ‘DD-MON-YY HH:MI:SS AM’)
“Central to Newfoundland”
from DUAL;
Your output is
Central to Newfoundland
22-FEB-97 07:30:00 AM
9. From Listing 6.22, subtract one month and explain the answer.
Two possible answers are
SELECT ADD_MONTHS(TO_DATE(‘31-MAR-97’),-1) from DUAL;
SELECT ADD_MONTHS(TO_DATE(‘31-MAR-97’),-1.5) from DUAL;
The output, of course, is the end of February because February has fewer than 30
days:
ADD_MONTH
28-FEB-97
A
29 7982 App 11.8.00 11:24 AM Page 629
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
10. Calculate the number of days until Christmas from the last day of the month of
today’s date. (We don’t get paid until the end of the month!)
Here is one solution:
SELECT LAST_DAY(SYSDATE) “Last_Day”,
TO_DATE(‘25-DEC-97’) - LAST_DAY(SYSDATE) “Shopping Days”
from DUAL;
The output is similar to
Last_Day Shopping Days
30-JUN-97 177.67266
Day 7, “Procedures, Packages, Errors, and
Exceptions”
Quiz
1. What statement do you use to recompile a procedure?
You use the
CREATE OR REPLACE PROCEDURE command to recompile a procedure.
2. How do you invoke a procedure?
You use the
execute command if you want to explicitly and manually call a proce-
dure. From within a package or another PL/SQL construct, you simply list the pro-
cedure name in the code, and the call to it is made automatically.
3. Name at least four predefined Oracle exception errors.
There are many Oracle predefined exceptions, including
no_data_found,
too_many_rows, invalid_cursor, value_error, invalid_number, zero_divide,
cursor_already_open, and login_denied.
4. How do you call a module of a package?
To call a specific procedure within a package, you use dot notation, as shown in
the following example:
package_name.procedure_name
Exercises
1. Write a package specification for the functions written in previous lessons.
Additionally, include in the specification one or two of the procedures used in this
lesson.
630 Appendix
29 7982 App 11.8.00 11:24 AM Page 630
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Answers 631
Package specifications contain public declarations of the name of the package and
its functions and procedures. The following is an example and might differ slightly
from your answer:
CREATE PACKAGE day_8_package_spec as
➥package
name declaration
FUNCTION inv_count (qty number, part_nbr varchar2(25)) function
declaration return number;
PROCEDURE pay_salary (emp_id number);
➥procedure
declaration
PROCEDURE hire_employee (emp_name, pay_date number, pay_type char));
➥procedure
declaration
END day_8_package_spec;
2. Write an exception-handling piece of code to trap the error of receiving more rows
than you expected as well as an unknown error.
One possible way to write this exception handler is
exception
WHEN too_many_rows THEN
code to be executed when a SELECT returns
too many rows
END;
WHEN others THEN
code to be executed when an exception is
encountered which is not the too_many_rows
Day 8, “Using SQL to Manipulate Data and
Control Transactions”
Quiz
1. Name some of the database objects that you can base a variable declaration on.
PL/SQL variables can be based on database table columns, other variables, con-
stants, and cursors.
2. Name at least two of the exception types discussed in this chapter.
There are many exceptions that a programmer can prepare for while coding. Some
of the most common are
no_data_found, too_many_rows, invalid_cursor, and
when_others.
A
29 7982 App 11.8.00 11:24 AM Page 631
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
3. Do you need to list the table column names while inserting data into that table?
No. If you elect to omit the column names during an insert statement, Oracle will
automatically align the input data with the columns of the data. The first piece of
data is inserted into the first column, the second piece of data will be inserted into
the second column, and so on.
4. What are the four SQL DML statements permitted in a PL/SQL block?
The four DML statements that are supported within a PL/SQL block are
INSERT,
DELETE, UPDATE, and SELECT.
Exercises
Evaluate each of the following three declarations and determine which ones are legal or
not legal. Explain your answer for those that are not legal.
1. Legal or not legal:
DECLARE
emp_rec emp_rec_type;
This is an invalid declaration because emp_rec_type must be declared prior to this
declaration. A proper declaration would be
DECLARE
TYPE emp_rec_type IS record
(id INTEGER,
name VARCHAR2(35));
emp_rec emp_rec_type;
2. Legal or not legal:
DECLARE
emp_last_name %type;
This is an invalid declaration. The proper declaration would have to include a table
and column reference such as
emp_last_name emp.l_name%type;
3. Legal or not legal:
DECLARE
TYPE emp_table_type is table of VARCHAR2(55);
emp_dept_table emp_table_type;
This declaration is incorrect because the INDEX BY clause is missing. This declara-
tion should look like
DECLARE
TYPE emp_table_type is table of VARCHAR2(55)
INDEX BY BINARY_INTEGER;
emp_dept_table emp_table_type;
632 Appendix
29 7982 App 11.8.00 11:24 AM Page 632
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Answers 633
Day 9, “Manipulating Data with Cursors”
Quiz
1. What are the cursor attributes and what is their purpose?
The implicit and explicit cursors each have four attributes, which provide useful
information about the cursor. These attributes are
%isopen, %found, %notfound, and
%rowcount.
2. How many cursors can you use at a time?
There are no predefined limits on the number of cursors a session can have. The
only constraint that limits the number of cursors is the availability of memory to
manage them.
3. Where is the cursor pointer when the cursor is first opened?
The cursor pointer is pointing to immediately prior to the first row when the cursor
is first opened.
4. Name the different cursor variable parameter modes and their purpose.
The cursor variable argument can have one of three different modes:
IN—The program can have read-only abilities with the parameter. In other words,
the cursor argument is passed only to the procedure or function.
OUT—The program can return values to the calling PL/SQL block.
IN OUT—The program can read and write to the variable.
Exercise
Create a PL/SQL block that determines the top five highest paid employees from
your Employee table. Be sure to incorporate the usage of the appropriate cursor
attributes. Print these five employees to the screen.
This exercise can be solved in several different ways. Your solution can include
exception handling as well as other methods of processing the data. I have chosen
the following method as my solution:
DECLARE
c_emp_name VARCHAR2(32);
c_sal NUMBER(9,2);
CURSOR emp_cursor is cursor declaration
SELECT emp_name, pay_type
from employee
ORDER BY pay_rate desc; key to getting top 5 highest paid employees
A
29 7982 App 11.8.00 11:24 AM Page 633
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
BEGIN
OPEN emp_cursor;
FETCH emp_cursor
INTO c_emp_name, c_sal; fetch into variables for later use
WHILE emp_cursor%rowcount<=5 and only fetch top 5 employees
emp_cursor%found be sure there is data
LOOP
DBMS_OUTPUT (c_emp_name || ‘ is paid ‘ || c_sal );
prints results to screen
FETCH emp_cursor INTO c_emp_name, c_sal;
END LOOP;
CLOSE emp_cursor; closes the cursor
END;
Day 10, “Collections”
Quiz
1. Name the three collection types PL/SQL supports.
The three collection types PL/SQL supports are index-by tables, nested tables, and
varrays.
2. What declaration would you use to declare a variable named
emp_name with a
datatype and size that exactly match the definition of the employee.emp_name col-
umn in the database?
In this case, the declaration would be
emp_name employee.emp_name%type.
3. What declaration would you use to declare a record named
emp that matches the
definition of a row in the employee table?
To declare
emp to match the employee table, use emp employee%rowtype.
4. What method can you call on to be sure that a collection element really exists?
The
exists method can be used to determine whether a given element exists.
5. What must you be sure to do before you can add data to a nested table or to a
varray?
Before you can do anything with a nested table or a varray, you must initialize it
with the value returned by its constructor function.
634 Appendix
29 7982 App 11.8.00 11:24 AM Page 634
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Answers 635
Exercise
Write the code necessary to generate a PL/SQL nested table with 10 new depart-
ment IDs and names. Use department ID numbers that are not currently being used
in the database. Make up the department names. Next, write a FORALL statement
that inserts all the records by using a bulk bind.
Here is one possible solution to the exercise:
1: DECLARE
2: Define a nested table type for department IDs and names.
3: TYPE dept_id IS TABLE OF department.dept_id%TYPE;
4: TYPE dept_name IS TABLE OF department.dept_name%TYPE;
5:
6: Declare a nested table variable for each type.
7: dept_ids dept_id;
8: dept_names dept_name;
9: inx1 PLS_INTEGER;
10: BEGIN
11: Initialize the collections
12: dept_ids := dept_id();
13: dept_names := dept_name();
14:
15: Extend once, outside the loop for better performance.
16: dept_ids.extend(10);
17: dept_names.extend(10);
18:
19: Generate 10 new departments, numbered from
20: 1101-1110.
21: FOR inx1 IN 1 10 LOOP
22: dept_ids(inx1) := inx1 + 1100;
23: dept_names(inx1) := ‘Dept #’ || TO_CHAR(inx1+1100);
24: END LOOP;
25:
26: FORALL x IN dept_ids.first dept_ids.last
27: INSERT INTO department (dept_id, dept_name)
28: VALUES (dept_ids(x), dept_names(x));
29: END;
30: /
The nested tables types are declared in lines 3–4. The corresponding variables are
declared in lines 7–8. The tables are initialized by calling their constructor meth-
ods in lines 12–13. Because we know that we are going to deal with only 10 elements,
only one call to extend is made for each table. These calls occur in lines 16–17, and they
extend each table by 10 entries. The loop in lines 21–24 generates 10 new departments,
numbered from 1101 through 1110. The FORALL statement in lines 26–28 inserts these
10 rows into the department table.
A
INPUT
ANALYSIS
29 7982 App 11.8.00 11:24 AM Page 635
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Day 11, “Writing Database Triggers”
Quiz
1. Which data manipulation statements can support triggers?
INSERT, UPDATE, and DELETE.
2. What are the four basic parts of a trigger?
The event that fires the trigger, the database table on which the trigger is defined,
the optional
WHEN clause, and the PL/SQL block containing the code to be
executed.
3. In a trigger, what are the correlation names
:OLD and :NEW used for?
:OLD is used to refer to the values in a row before it is changed. :NEW is used to
refer to the values after the row is changed.
4. What is the name of the system view that can be used to retrieve trigger defini-
tions?
The
USER_TRIGGERS view shows all triggers you own. In addition, you might want
to look at the ALL_TRIGGERS view and the DBA_TRIGGERS view. The ALL_TRIGGERS
view adds triggers that others own but which are defined on your tables. If you
have database administrator privileges, the DBA_TRIGGERS view lists all triggers
defined in the database.
5. What is a mutating table?
A mutating table is one that is in the process of being modified by the SQL state-
ment which fired a trigger. Because the table is being changed it is not in a consis-
tent state and Oracle does not allow queries against it.
6. Name some possible uses for triggers.
Some possible uses for triggers are enforcing a business rule, enforcing security,
logging changes, replicating data, and calculating column values.
Exercises
1. Write a set of triggers to maintain the emp_name and dept_name fields redundantly
in the emp_dept relation so that you do not have to join the employee and depart-
ment tables just to get a simple department listing.
636 Appendix
29 7982 App 11.8.00 11:24 AM Page 636
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... 286-288 exception-handling, 288-289 index-by tables, 266 declaring, 266-267 deleting entries, 270-271 inserting entries into, 267-268 methods, 271-274 referencing values, 268-269 updating entries, 270 nested tables, 274 adding entries to, 275-278 declaring, 275 extending, 277-278 initializing, 276-277 removing entries, 279-281 variable-sized arrays, 281 adding\removing data, 283-284 declaring, 282-283 ... Advanced Queuing, see AQ after triggers, 296 agents, AQ (Advanced Queuing), 587 alerts monitoring any, 535 monitoring one, 534-535 polling (setting time interval), 536 registering, 533-534 660 alerts removing, 557 all, 536 one, 535 security example, 536-543 backup database, 537-538 signaling with DELETE, 541-542 signaling with INSERT, 540 signaling with UPDATE, 541 trigger, 538-539 viewing trigger results,... Gennick” OUTPUT PL/SQL procedure successfully completed ANALYSIS Lines 11–27 contain the read loop Here, each line is read from the file and dis- played by using DBMS_OUTPUT The actual read is embedded within a nested PL/SQL block (lines 12–19) because of the need to detect the end-of-file Encountering an end-of-file will result in a NO_DATA_FOUND exception being raised This is trapped in lines 15–16,... the building object This stored function serves as a psuedo-constructor Note however, that Oracle can’t force you to call this inBldgName VARCHAR2, inBldgStreet VARCHAR2, inBldgCity VARCHAR2, inBldgStateAbbr VARCHAR2, inBldgZip VARCHAR2, inBldgMgr employee.emp_id%TYPE ) RETURN building AS TheNewBldg building; NoFlag integer; BEGIN Check to see if this building already exists SELECT count(*) INTO NoFlag... 402 adding to tables, 423-424 assigning locator to, 419 editing, 428 EMPTY_CLOB function, 416, 419 initializing, 160 CLOSE command, 251 CLOSE_CURSOR procedure, 456 closing cursors (CLOSE command), 251 code formatting, 395-396 indentation, 396 keyword capitalization, 397 number of statements per line, 397 variable names, 397 trigger viewing, 309-310 see also listings collections, 265 bulk-binding, 284... statement in lines 27–29 checks to be sure ANALYSIS 641 A 642 Appendix that the manager ID is a valid employee ID If everything checks out, the building constructor is called in lines 37–44 to actually create the building object, which is then returned to the calling program (see line 46) The PL/SQL block at the end of the listing (lines 50–74) shows the results of three attempts to create building objects... retyping, 18 Notepad cut and paste, 18 SQL*Plus @ command, 18-19 SQL*Plus EDIT command, 19-20 anon, 467, 469 listing, 469-470 retrieving values with, 468-469 anonymous, 49 listing, 50-51 syntax, 49-50 661 block structured languages, 13 compiling and executing, 15-17 debugging (Procedure builder), 24-28 executing (SQLPlus Worksheet), 28-29 formatting (indenting), 396 function, 51 syntax, 51-52 nesting,... END; / Type body created This version of the building object is much the same as the one you first created from Listing 12.7, except that it has a MAP function defined instead of an ORDER function This MAP function, declared in lines 6–7 and defined in lines 18–22 of the second segment, simply returns the building name When comparing objects of type building, Oracle will call this function and base the... Write a PL/SQL block that establishes a savepoint, inserts a single record into the employee table, commits the data if the new record does not replicate an existing record, or rolls back the data if the new record insert fails Here is one solution: SAVEPOINT exercise; use this to roll back to INSERT INTO employee VALUES (10, ‘Loraine Williams’,2,4000.00,’S’); COMMIT; saves the data if insert was... 26: Return the information that was dequeued 27: emp_id := payload.emp_id; 28: old_dept := payload.leave_dept; 29: new_dept := payload.join_dept; 30: END; 31: / ANALYSIS The code in this listing is very similar to that in Listing 21. 6 However, there are some differences worth noting First, the dbms_aq.forever constant is used in line 16 to prevent the dequeue procedure from returning without a message . String1 to’,
‘ String2’);
v_String2 VARCHAR2(60) := ‘Connect String1 to’ || ‘ String2’;
BEGIN
DBMS_OUTPUT.PUT_LINE(v_String1);
DBMS_OUTPUT.PUT_LINE(v_String2);
END;
/
Your. 1101-1110.
21: FOR inx1 IN 1 10 LOOP
22: dept_ids(inx1) := inx1 + 1100;
23: dept_names(inx1) := ‘Dept #’ || TO_CHAR(inx1+1100);
24: END LOOP;
25:
26: FORALL x IN