Vous êtes sur la page 1sur 23

Oracle Academy Introduction to PL/SQL Instructor Resource Guide

INSTRUCTOR NOTES FOR SLIDES


SECTION 7 LESSON 1 Slide 1: Creating Procedures No instructor notes for this slide Slide 2: What Will I Learn? No instructor notes for this slide Slide 3: Why Learn It? No instructor notes for this slide Slide 4: Tell Me / Show Me Differences Between Anonymous Blocks and Subprograms Remind students that every object stored in the database tables, views, indexes, synonyms, sequences, and now PL/SQL subprograms must have a name. Slide 5: Tell Me / Show Me Differences Between Anonymous Blocks and Subprograms (continued) No instructor notes for this slide Slide 6: Tell Me / Show Me Differences Between Anonymous Blocks and Subprograms (continued) Point out that the keyword DECLARE is replaced by CREATE PROCEDURE procedure-name IS|AS. In anonymous blocks, DECLARE states this is the start of a block. Because CREATE PROCEDURE states this is the start of a subprogram, we do not need (and must not use) DECLARE. Slide 7: Tell Me / Show Me Differences Between Anonymous Blocks and Subprograms (continued) No instructor notes for this slide Slide 8: Tell Me / Show Me Benefits of Subprograms Code Reuse: for example (in a school or college database) a single PL/SQL procedure which accepts a student id number as a parameter and outputs a complete record describing that student. This procedure could be used in a Student Grades application, also in a Sports Teams application, also in a Student Health application . in fact in any application which needs information about a student.

Oracle Academy

1 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Slide 9: Tell Me / Show Me Benefits of Subprograms (continued) Students will learn more about subprogram security and required privileges in Section 8. For now, the first bullet on the slide means that if a subprogram contains a SQL statement which SELECTs from a table, the subprogram owner needs SELECT privilege on that table, but the user does not. This means that the only way the user can access the table is through the subprogram, not by any other route. Therefore the user cannot see sensitive or confidential data unless the subprogram code explicitly allows it. Slide 10: Tell Me / Show Me Benefits of Subprograms (continued) Improved performance: a subprogram is compiled only once, when it is (re)CREATEd. An anonymous block is compiled (while the user waits) every time it is executed. Slide 11: Tell Me / Show Me Procedures and Functions If students ask about Packages at this point, tell them that a package is a group of several related procedures and/or functions which are created and managed as a single unit. Packages are very powerful and important, but the building blocks are still procedures and functions. Slide 12: Tell Me / Show Me What is a Procedure? Section 8 includes a review of these USER_* data dictionary views. Slide 13: Tell Me / Show Me Syntax for Creating Procedures Students will learn more about parameters and their modes in the next two lessons. Slide 14: Tell Me / Show Me Syntax for Creating Procedures (continued) There is no difference in meaning between IS and AS, either can be used. Slide 15: Tell Me / Show Me Procedure: Example No instructor notes for this slide Slide 16: Tell Me / Show Me Procedure Example (continued) In a real-life procedure the v_dept_id and v_dept_name values would be passed into the procedure as parameters, not hard-coded as shown here. This procedure does not have (but should have) an EXCEPTION section. Slide 17: Tell Me / Show Me Invoking Procedures No instructor notes for this slide Slide 18: Tell Me / Show Me Invoking the Procedure from Application Express After you execute the above, delete the row by executing the following: DELETE FROM dept WHERE department_id = 280; Slide 19: Tell Me / Show Me Correcting Errors in Create Procedure Statements When a subprogram is CREATEd, the source code is stored in the database (therefore the named code object is created) even if compilation errors occurred. This is why we need . OR REPLACE Oracle Academy 2 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Slide 20: Tell Me / Show Me Saving Your Work No instructor notes for this slide Slide 21: Tell Me / Show Me Saving Your Work (continued) No instructor notes for this slide Slide 22: Tell Me / Show Me Saving Your Work (continued) No instructor notes for this slide Slide 23: Tell Me / Show Me Alternative Tools for Developing Procedures To develop a stored procedure when not using Oracle Application Express, perform the following steps: 1. Write the code to create a procedure in an editor or a word processor, and then save it as a SQL script file (typically with a .sql extension). 2. Load the code into one of the development tools such as iSQL*Plus or SQL Developer. 3. Create the procedure in the database. The CREATE PROCEDURE statement compiles and stores source code and the compiled m-code in the database. If compilation errors exist, then the m-code is not stored and you must edit the source code to make corrections. 4. After successful compilation, execute the procedure to perform the desired action. Use the EXECUTE command from iSQL*Plus or an anonymous PL/SQL block from environments that support PL/SQL. Slide 24: Tell Me / Show Me Terminology Anonymous Blocks Unnamed executable PL/SQL blocks that can not be reused no stored for later use. Subprograms Named PL/SQL blocks that are compiled and stored in the database. Procedures Named PL/SQL blocks that can accept parameters and are compiled and stored in the database. Slide 25: Summary No instructor notes for this slide Slide 26: Try It / Solve It No instructor notes for this slide

Oracle Academy

3 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

SECTION 7 LESSON 2 Slide 1: Using Parameters in Procedures No instructor notes for this slide Slide 2: What Will I Learn? No instructor notes for this slide Slide 3: Why Learn It? No instructor notes for this slide Slide 4: Tell Me / Show Me What are Parameters? No instructor notes for this slide Slide 5: Tell Me / Show Me What are Parameters? (continued) Answer: normally you would not need to know the old (before) value. The next slide shows the procedure code. Slide 6: Tell Me / Show Me What are Parameters? (continued) Explain that the UPDATE statement would be coded as: UPDATE grade_table SET grade = p_grade WHERE student_id = p_student_id AND class_id = p_class_id; Slide 7: Tell Me / Show Me What are Arguments? Parameter means the name, argument means the value. In the example on the previous slide, p_student_id is a parameter while 1023 is an argument. Slide 8: Tell Me / Show Me Creating Procedures with Parameters? No instructor notes for this slide Slide 9: Tell Me / Show Me Invoking Procedures with Parameters No instructor notes for this slide Slide 10: Tell Me / Show Me Invoking Procedures with Parameters (continued) In this example, the process_employees stored procedure uses a cursor to process all the records in the EMPLOYEES table and passes each employees ID to the RAISE_SALARY procedure. If there are 20 rows in the EMPLOYEES table, RAISE_SALARY will execute 20 times. Every employee in turn receives a 10% salary increase. Slide 11: Tell Me / Show Me Types of Parameters p_emp_id is the formal parameter and v_emp_id is the actual parameter. We make the distinction because the names can be different (as in this example). However, the datatypes must be compatible. Slide 12: Tell Me / Show Me Formal Parameters No instructor notes for this slide Oracle Academy 4 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Slide 13: Tell Me / Show Me Actual Parameters Because 2000 is a literal, not the name of a variable, it is both the actual parameter and the argument. Slide 14: Tell Me / Show Me Formal and Actual Parameters No instructor notes for this slide Slide 15: Tell Me / Show Me Terminology Parameters Pass or communicate data between the caller and subprogram and are commonly referred to as arguments. Formal Parameter A parameter name declared in the procedure heading. Actual Parameter Can be literal values, variables or expressions that are provided in the parameter list of a called subprogram. Slide 16: Summary No instructor notes for this slide Slide 17: Try It / Solve It No instructor notes for this slide

Oracle Academy

5 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

SECTION 7 LESSON 3 Slide 1: Passing Parameters No instructor notes for this slide Slide 2: What Will I Learn? No instructor notes for this slide Slide 3: Why Learn It? No instructor notes for this slide Slide 4: Tell Me / Show Me Procedural Parameter Modes No instructor notes for this slide Slide 5: Tell Me / Show Me The IN mode is the default if no mode is specified. Students should think of IN parameters as constants within the procedure. They can be read but not modified. Slide 6: Tell Me / Show Me Using OUT Parameters: Example No instructor notes for this slide Slide 7: Tell Me / Show Me Using the previous OUT example No instructor notes for this slide Slide 8: Tell Me / Show Me Viewing OUT Parameters in Application Express No instructor notes for this slide Slide 9: Tell Me / Show Me Using IN OUT Parameters: Example Remind students that all formal parameters must be declared with datatypes but not explicit sizes. In the slide example, p_phone_no is declared as VARCHAR2, not VARCHAR2(n). The only exception to this rule is when a parameters datatype is declared implicitly, ie when using %TYPE. Slide 10: Tell Me / Show Me Using the previous IN OUT example No instructor notes for this slide Slide 11: Tell Me / Show Me Calling the previous IN OUT example No instructor notes for this slide Slide 12: Tell Me / Show Me Summary of Parameter Modes Students will learn about default values for IN parameters later in this lesson. Slide 13: Tell Me / Show Me Syntax for Passing Parameters All the earlier examples in this section used the Positional notation.

Oracle Academy

6 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Slide 14: Tell Me / Show Me Parameter Passing: Examples No instructor notes for this slide Slide 15: Tell Me / Show Me Parameter Passing No instructor notes for this slide Slide 16: Tell Me / Show Me Parameter Passing (continued) No instructor notes for this slide Slide 17: Tell Me / Show Me Using the DEFAULT Option for IN Parameters No instructor notes for this slide Slide 18: Tell Me / Show Me Using the DEFAULT Option for Parameters In Application Express, DESCRIBE procedure-name does not show which parameters have default values. Some other languages allow something like add_dept(,1200) where the comma indicates the missing parameter. PL/SQL does not. Slide 19: Tell Me / Show Me Guidelines for Using the DEFAULT Option for Parameters The named notation for passing parameters is especially useful when the called procedure contains many IN parameters, many of which have default values. Imagine a procedure which declares 10 N parameters, all of which have default values. We want to call the procedure, overriding the default value only for the last parameter. We can simply code: . procedure_name(last_parameter_name => value); Using the positional notation, all ten values must be passed, and the default values could not be used. Slide 20: Tell Me / Show Me Working with Parameter Errors During Runtime No instructor notes for this slide Slide 21: Tell Me / Show Me Terminology IN Parameter Provides values for a subprogram to process. OUT Parameter Returns a value to the caller. IN OUT Parameter Supplies an input value, which may be returned as a modified value. Slide 22: Summary No instructor notes for this slide Slide 23: Try It / Solve It No instructor notes for this slide

Oracle Academy

7 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

PRACTICE SOLUTIONS
SECTION 7 LESSON 1 - Creating Procedures Terminology 1. _Subprograms______________ Named PL/SQL blocks that are compiled and stored in the database. 2. __Anonymous Blocks________ Unnamed executable PL/SQL blocks that cannot be reused or stored for later use. 3. __Procedures________________ Named PL/SQL blocks that can accept parameters and are compiled and stored in the database. Try It / Solve It 1. What is the difference between the following two pieces of code? --CODE SAMPLE A DECLARE v_empid employees.employee_id%TYPE := 100; v_percent_increase NUMBER(2,2) := .05; BEGIN UPDATE employees SET salary = (salary * percent_increase) + salary WHERE employee_id = v_empid; END; --CODE SAMPLE B CREATE PROCEDURE pay_raise (p_empid employees.employee_id%TYPE, p_percent_increase NUMBER) IS BEGIN UPDATE employees SET salary = (salary * p_percent_increase) + salary WHERE employee_id = p_empid; END pay_raise; Code sample A is an anonymous block which is an unnamed block of code with the following characteristics: Is not stored in the database Compiled each time it is used Cannot be invoked by applications Cannot take parameters Cannot return values

Oracle Academy

8 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Code Sample B is a subprogram named pay_raise. It has the following characteristics: Compiled once and stored in the database Invoked by name in applications Can have parameters passed to it Can return values (a function must return a value) 2. In your own words, list the benefits of subprograms. Subprograms are easy to maintain, can be re-used, improve data security and data integrity, improve performance, and improve readability of code. 3. In your own words, describe what a stored procedure is. A procedure is a named subprogram that is compiled and stored in the database as an object in a schema. It can accept parameters and can return values. A procedure performs an action and can be re-used. 4. The remaining questions in this practice use a copy of the employees table. A. Create the copy by executing the following SQL statement: CREATE TABLE employees_dup AS SELECT * from employees; B. Create the following procedure in Application Express: CREATE OR REPLACE PROCEDURE name_change IS BEGIN UPDATE employees_dup SET first_name = Susan WHERE department_id = 80; END pay_raise; C. Save the definition of your procedure in case you need to modify it later. In the Save SQL popup, name your saved work My name change procedure. D. Execute the procedure by running the following anonymous block: BEGIN name_change; END;

Oracle Academy

9 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

E. SELECT from the table to check that the procedure has executed correctly and performed the UPDATE: SELECT first_name, department_id FROM employees_dup;

5. Create a second procedure named pay_raise which changes the salary of all employees in employees_dup to a new value of 30000. Execute the procedure from anonymous block, then SELECT from the table to check that procedure has executed correctly. CREATE OR REPLACE PROCEDURE pay_raise IS BEGIN UPDATE employees_dup SET SALARY = 30000; END pay_raise; BEGIN pay_raise; END; SELECT employee_id, salary FROM employees_dup; 6. Retrieve your first name_change procedure by clicking on its name in the Saved SQL window. Modify the code to remove OR REPLACE from the CREATE statement, and introduce a deliberate error into the code, for example by misspelling a keyword: UPDAT employees_dup. Execute your code to recreate the procedure. What happens? CREATE PROCEDURE name_change IS BEGIN UPDAT employees_dup SET first_name = Susan WHERE department_id = 80; END pay_raise; An ORA-00955 error is returned because the procedure is already stored in the database. 7. Now correct the procedure code by reinserting the OR REPLACE clause and correcting your deliberate spelling error. Execute your code to recreate the procedure. Now what happens? The execution is successful and the modified procedure is recreated.

Oracle Academy

10 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Extension Exercise 1. Create, save and execute a procedure which updates the salary of employees in employees_dup according to the following rules: if the employee is in department 80, their new salary must = 1000 if the employee is in department 50, their new salary must = 2000 if the employee is in any other department, their new salary must = 3000.

You will need to include three UPDATE statements, one for each of the above rules. In a later lesson you will learn how to avoid this. Execute your procedure from an anonymous block and verify that the updates have been performed correctly. CREATE OR REPLACE PROCEDURE sal_change IS BEGIN UPDATE employees_dup SET salary = 1000 WHERE department_id = 80; UPDATE employees_dup SET salary = 2000 WHERE department_id = 50; UPDATE employees_dup SET salary = 3000 WHERE department_id NOT IN (80, 50); END sal_change; BEGIN Sal_change; END; SELECT employee_id, department_id, salary FROM employees_dup;

Oracle Academy

11 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

SECTION 7 LESSON 2 - Using Parameters in Procedures Terminology 1. _Parameters_______________ Pass or communicate data between the caller and subprogram and are commonly referred to as arguments. 2. _Actual Parameter__________ Can be literal values, variables or expressions that are provided in the parameter list of a called subprogram. 3. _Formal Parameter__________ A parameter name declared in the procedure heading. Try It / Solve It 1. In your own words, describe parameters and the purpose they serve in PL/SQL subprograms. Parameters are used to pass values that may vary into a subprogram. They can also be used by a subprogram to compute new values and return them to the calling environment. They make procedures more flexible; a procedure can be created once and then executed many times with different values for the parameters. 2. Using the wf_countries table. A. Create a procedure that accepts a country_id as a parameter and displays the name of the country and its capitol city. Name your procedure get_country_info. Save your procedure definition for later use. CREATE OR REPLACE PROCEDURE get_country_info (p_country_id IN wf_countries.country_id%TYPE) IS v_country_name wf_countries.country_name%TYPE; v_capitol wf_countries.capitol%TYPE; BEGIN SELECT country_name, capitol INTO v_country_name, v_capitol FROM wf_countries WHERE country_id = p_country_id; DBMS_OUTPUT.PUT_LINE('The country name is '||v_country_name|| and the capital city is '||v_capitol); END; B. Execute your procedure from an anonymous block, using country_id 90. BEGIN get_country_info(90); END; The country name is Republic of Turkey and the capital city is Ankara.

Oracle Academy

12 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

C. Re-execute the procedure from the anonymous block, this time using country_id 95. What happens? An ORA-01403 error is returned because country_id 95 does not exist. D. Retrieve your procedure code from Saved SQL and modify it to trap the NO_DATA_FOUND exception in an exception handler. Re-execute the procedure using country_id 95 again. Now what happens? CREATE OR REPLACE PROCEDURE get_country_info (p_country_id IN wf_countries.country_id%TYPE) IS v_country_name wf_countries.country_name%TYPE; v_capitol wf_countries.capitol%TYPE; BEGIN SELECT country_name, capitol INTO v_country_name, v_capitol FROM wf_countries WHERE country_id = p_country_id; DBMS_OUTPUT.PUT_LINE('The country name is '||v_country_name|| and the capital city is '||v_capitol); EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(This country does not exist); END; The NO_DATA_FOUND exception has been trapped within the procedure code. 3. In your own words, describe what a formal parameter is and what an actual parameter is. Also name three variations for an actual parameter. A formal parameter is the parameter in the header of a procedure that gives the parameter a name and datatype. The formal parameter name is referenced within the procedure code. An actual parameter is the value passed from the calling environment when the procedure is executed. Actual parameters can be expressions, literal values, or variables.

Oracle Academy

13 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

4. Procedure Exercise: A. Write a procedure that displays the number of countries in a given region whose highest elevation exceeds a given value. The procedure should accept 2 formal parameters, one for a region_id and the other for a highest elevation. Use DBMS_OUTPUT.PUT_LINE to display the results in a message. Save your procedure code.

CREATE OR REPLACE PROCEDURE get_country_count (p_region id wf_countries.region_id%TYPE, p_elevation wf_countries.highest_elevation%TYPE) IS v_count NUMBER(4); BEGIN SELECT COUNT(*) INTO v_count FROM wf_countries WHERE region_id = p_region_id AND highest_elevation > p_elevation; DBMS_OUTPUT.PUT_LINE ('Region '||p_region_id|| contains ||v_count|| countries higher than ||p_elevation); END; B. Execute your procedure using the value 5 for the region_id and 2000 for the highest elevation. BEGIN get_country_count(5,2000); END; Region 5 contains 10 countries higher than 2000 C. DESCRIBE your procedure to check the names and datatypes of its formal parameters. DESCRIBE get_country_count

Oracle Academy

14 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

D. Retrieve your procedure code from Saved SQL and modify it to accept a third formal parameter for a minimum area. The procedure should display a count of the number of countries in a given region whose highest elevation exceeds a given value and whose country name starts with a given alphabetic character. Your SELECT statement should include a WHERE condition to compare the first character of each countrys name with the third parameter value (Hint: use SUBSTR). Save your work again and DESCRIBE the modified procedure. CREATE OR REPLACE PROCEDURE get_country_count (p_region id wf_countries.region_id%TYPE, p_elevation wf_countries.highest_elevation%TYPE, p_char CHAR) IS v_count NUMBER(4); BEGIN SELECT COUNT(*) INTO v_count FROM wf_countries WHERE region_id = p_region_id AND highest_elevation > p_elevation AND SUBSTR(country_name,1,1) = p_char; DBMS_OUTPUT.PUT_LINE ('Region '||p_region_id|| contains ||v_count|| countries higher than ||p_elevation|| whose name starts with ||p_char); END; DESCRIBE get_country_count E. Write an anonymous block which declares three variables to store actual parameter values for the region_id, elevation and area, then executes the procedure passing these values. Execute the block using values 5, 2000 and B. DECLARE v_region_id wf_countries.region_id%TYPE := 5; v_elevation wf_countries.highest_elevation%TYPE := 2000; v_char CHAR(1) := B; BEGIN get_country_count(v_region_id, v_elevation, v_char); END; Region 5 contains 10 countries higher than 2000 whose name starts with B

Oracle Academy

15 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

F. Modify your anonymous block to use the same actual parameter values but pass them to the procedure in a different order: (5, B, 2000). Execute the block. What happens and why? DECLARE v_region_id wf_countries.region_id%TYPE := 5; v_elevation wf_countries.highest_elevation%TYPE := 2000; v_char CHAR(1) := B; BEGIN get_country_count(v_region_id, v_char, v_elevation); END; An ORA-06502 data conversion error is returned because the procedure call cannot convert an actual parameter (B) of datatype CHAR to a formal parameter of datatype NUMBER.

Oracle Academy

16 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

SECTION 7 LESSON 3 - Passing Parameters Terminology 1. _OUT Parameter___________ Returns a value to the caller. 2. _IN Parameter_____________ Provides values for a subprogram to process. 3. _IN OUT Parameters_________ Supplies an input value, which may be returned as a modified value. Try It / Solve It 1. Name the three modes for parameters and indicate which mode is the default mode. Which mode cannot be modified inside the procedure? IN the default. Caon only be read (not modified) inside the procedure. IN OUT OUT 2. Procedures: Create a procedure that receives a country_id as an IN parameter and returns the name and population of that country as OUT parameters. Include an exception handler to trap the NO_DATA_FOUND exception if the country does not exist. The procedure should not display the returned values; this will be done in the next step. Name your procedure find_area_pop. Save your code. CREATE OR REPLACE PROCEDURE find_area_pop (p_country_id IN wf_countries.country_id%TYPE, p_country_name OUT wf_countries.country_name%TYPE, p_population OUT wf_countries.population%TYPE) IS BEGIN SELECT country_name, population INTO p_country_name, p_population FROM wf_countries WHERE country_id = p_country_id; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE(Country id: || p_country_id || does not exist); END;

Oracle Academy

17 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Test your procedure by creating and executing an anonymous block which invokes the procedure and displays the returned about values. Save your code. Run the block twice, with country_ids 2 (Canada) and 10 (does not exist). . DECLARE v_country_id wf_countries.country_id%TYPE; v_country_name wf_countries.country_name%TYPE; v_population wf_countries.population%TYPE; BEGIN v_country_id := <enter a country id>; -- 2 then 10 find_area_pop(v_country_id, v_country_name, v_population); DBMS_OUTPUT.PUT_LINE('Name: ' || v_country_name || ' Population: || v_population); END; Retrieve your procedure code and modify it to add a third OUT parameter which is the population density of the country, using the formula: density = (population / area). You will need to modify your SELECT statement to fetch the area column value into a local variable. Save your modified code. CREATE OR REPLACE PROCEDURE find_area_pop (p_country_id IN wf_countries.country_id%TYPE, p_country_name OUT wf_countries.country_name%TYPE, p_population OUT wf_countries.population%TYPE, p_pop_density OUT NUMBER) IS v_area wf_countries.area%TYPE; BEGIN SELECT country_name, population, area INTO p_country_name, p_population, v_area FROM wf_countries WHERE country_id = p_country_id; p_pop_density := p_population / v_area; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('Country id: '|| p_country_id || ' does not exist'); END;

Oracle Academy

18 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Test your modifed procedure using country_id 2. You will need to modify your calling anonymous block to declare and pass a fourth actual parameter to receive the population density from the procedure. DECLARE v_country_id wf_countries.country_id%TYPE; v_country_name wf_countries.country_name%TYPE; v_population wf_countries.population%TYPE; v_pop_density NUMBER(8,2); BEGIN v_country_id := 2; find_area_pop(v_country_id, v_country_name, v_population, v_pop_density); DBMS_OUTPUT.PUT_LINE('Name: ' || v_country_name || ' Population: ' || v_population || ' Density: '|| v_pop_density || ' per square km'); END; 3. Create a procedure which accepts an integer as an IN OUT parameter and returns the square of that integer, for example the square of 4 is 16. Save your code. Test your procedure from an anonymous block three times, using integer values 4, 7 and 20 (minus 20). CREATE OR REPLACE PROCEDURE squareit (p_integer IN OUT INTEGER) IS BEGIN p_integer := p_integer **2; END; DECLARE v_integer INTEGER; BEGIN v_integer := <enter an integer>; -- 4, 7, -20 squareit(v_integer); DBMS_OUTPUT.PUT_LINE('The answer is: ' || v_integer); END; 4. List the three methods of passing parameters to a procedure. Positional notation, Named notation and Combination notation.

Oracle Academy

19 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Retrieve your anonymous block from question 2d and modify its call to find_area_pop to pass the four parameters using named notation. Test your block, again using country_id 2 (Canada). If you had forgotten the p_* names of the procedures formal parameters, how would you refresh your memory ? DECLARE v_country_id wf_countries.country_id%TYPE; v_country_name wf_countries.country_name%TYPE; v_population wf_countries.population%TYPE; v_pop_density NUMBER(8,2); BEGIN v_country_id := 2; find_area_pop(p_country_id => v_country_id, p_country_name => v_country_name, p_population => v_population, p_pop_density => v_pop_density); DBMS_OUTPUT.PUT_LINE('Name: ' || v_country_name || ' Population: ' || v_population || ' Density: '|| v_pop_density || ' per square km'); END; You can see the names and datatypes of the formal parameters by: DESCRIBE procedure_name Modify the anonymous block from the previous step to pass the FIRST two parameters using named notation and the LAST two using positional notation. Test the block again. What happens? An error is returned because when using the combination notation, positional notation parameters must be listed before named notation parameters

Oracle Academy

20 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Correct the problem in the previous step by modifying the anonymous block again to pass the first two parameters using positional notation and the last two using named notation. Test the block again. DECLARE v_country_id wf_countries.country_id%TYPE; v_country_name wf_countries.country_name%TYPE; v_population wf_countries.population%TYPE; v_pop_density NUMBER(8,2); BEGIN v_country_id := 2; find_area_pop(v_country_id, v_country_name, p_population => v_population, p_pop_density => v_pop_density); DBMS_OUTPUT.PUT_LINE('Name: ' || v_country_name || ' Population: ' || v_population || ' Density: '|| v_pop_density || ' per square km'); END; 5. In your own words, describe the purpose of the DEFAULT option for parameters, and state the two syntax options for providing the default value in the procedure header. The purpose of the DEFAULT option for parameters is to provide an automatic value to be used in cases where a value is not passed from the calling environment. The default value may be provided using either DEFAULT <value> or := <value>. 6. Find the country_id of your own country by executing a suitable SQL SELECT FROM wf_countries . Then retrieve your find_area_pop procedure from question 2. Modify the code to use your country_id as a default value for the country_id IN parameter. Save your code. Then retrieve your anonymous block from question 2d and modify it so that it does NOT pass the country_id to the procedure. Test the block and check that your countrys details are returned and displayed.

Oracle Academy

21 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

CREATE OR REPLACE PROCEDURE find_area_pop (p_country_id IN wf_countries.country_id%TYPE DEFAULT <your_country_id>, p_country_name OUT wf_countries.country_name%TYPE, p_population OUT wf_countries.population%TYPE, p_pop_density OUT NUMBER) IS v_area wf_countries.area%TYPE; BEGIN SELECT country_name, population, area INTO p_country_name, p_population, v_area FROM wf_countries WHERE country_id = p_country_id; p_pop_density := p_population / v_area; EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE('Country id: '|| p_country_id || ' does not exist'); END; DECLARE v_country_id wf_countries.country_id%TYPE; v_country_name wf_countries.country_name%TYPE; v_population wf_countries.population%TYPE; v_pop_density NUMBER(8,2); BEGIN v_country_id := 2; -- not needed anymore find_area_pop(p_country_name => v_country_name, p_population => v_population, p_pop_density => v_pop_density); DBMS_OUTPUT.PUT_LINE('Name: ' || v_country_name || ' Population: ' || v_population || ' Density: '|| v_pop_density || ' per square km'); END; Because the first parameter is not being passed, the reamaining parameters must be changed to use Named notation.

Oracle Academy

22 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Extension Exercise 1. Create and test a procedure which accepts a department id as an IN parameter with a default value of 50, and returns (using OUT parameters) the last name and salary of the employee in that department who has the highest salary. The SELECT statement in the procedure should use a subquery. Test your procedure twice from an anonymous block, the first time using department id 80, the second time using the default value. CREATE OR REPLACE PROCEDURE highest_sal (p_dept_id IN employees.department_id%TYPE DEFAULT 50, p_last_name OUT employees.last_name%TYPE, p_salary OUT employees.salary%TYPE) IS BEGIN SELECT last_name, salary INTO p_last_name, p_salary FROM employees e WHERE department_id = p_dept_id AND salary = (SELECT MAX(salary)FROM employees WHERE department_id = e.department_id); END; /* Passing the department_id explicitly */ DECLARE v_last_name employees.last_name%TYPE; v_salary employees.salary%TYPE; BEGIN highest_sal(80, v_last_name, v_salary); DBMS_OUTPUT.PUT_LINE('Last name: ' || v_last_name || ' earns: ' || v_salary); END; /* Using the default value */ DECLARE v_last_name employees.last_name%TYPE; v_salary employees.salary%TYPE; BEGIN highest_sal(p_last_name => v_last_name, p_salary => v_salary); DBMS_OUTPUT.PUT_LINE('Last name: ' || v_last_name || ' earns: ' || v_salary); END;

Oracle Academy

23 Database Programming with PL/SQL Copyright 2007, Oracle. All rights reserved.

Vous aimerez peut-être aussi