23

Click here to load reader

PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

  • Upload
    lamminh

  • View
    216

  • Download
    2

Embed Size (px)

Citation preview

Page 1: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Benefits of Modular CodeA PL/SQL module is any complete logical unit of work. There are four types of PL/SQL modules: 1. anonymous blocks that are run with a text script (this is the type you have used until now);2) procedures;3) functions;4) packages.There are two main benefits to using modular code:

1) it is more reusable;2) it is more manageable.

You create a procedure either in SQL*Plus or in one of the many tools for creating and debugging stored PL/SQL code. If you are using SQL*Plus, you will need to write your code in a text editor and then run it at the SQL*Plus prompt.The block structure is common for all the module types. The block begins with a header (for named blocks only), which consists of (1) the name of the module, and (2) a parameter list (if used).The Declaration section consists of variable, cursors, and subblocks that will be needed in the next section.The main part of the module is the Execution section, where all the calculations and processing is performed. This will contain executable code such as IF-THEN-ELSE, LOOPS, calls to other PL/SQL modules, and so on.The last section of the module is an optional exception handler, which is where the code to handle exceptions is placed.

1

Page 2: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Anonymous block and procedureAnonymous blocks are very much the same as modules, which were just introduced (except anonymous blocks do not have headers). There are important distinctions, though. As the name implies, anonymous blocks have no name and thus cannot be called by another block. They are not stored in the database and must be compiled and then run each time the script is loaded.The PL/SQL block in a subprogram is a named block that can accept parameters and can be invoked from an application that can communicate with the Oracle database server. A subprogram can be compiled and stored in the database. This allows the programmer to reuse the program. It also provides for easier maintenance of code. Subprograms are either procedures or functions.A procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows:

CREATE OR REPLACE PROCEDURE name [(parameter[, parameter, ...])]AS [local declarations]BEGIN executable statements[EXCEPTION exception handlers]END [name];

A procedure may have 0 to many parameters. This will be covered in the next lab. Every procedure has two parts: (1) the header portion, which comes before AS (sometimes you will see IS—they are interchangeable), keyword (this contains the procedure name and the parameter list), and (2) the body, which is everything after the IS keyword. The word REPLACE is optional. When the word REPLACE is not used in the header of the procedure, in order to change the code in the procedure, the procedure must be dropped first and then re-created. Since it is very common to change the code of the procedure, especially when it is under development, it is strongly recommended to use the OR REPLACE option.

2

Page 3: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Package DBMS_OUTPUT

Put Get

set SERVEROUTPUT on size 500 000; vai DBMS_OUTPUT.ENABLE (500 000);

Server text buffer

3

Page 4: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Use of DBMS_OUTPUT package

SQL> set SERVEROUTPUT on size 100000SQL> begin

2 DBMS_OUTPUT.PUT_LINE('Beginning');3 for counter in 1..5 loop4 DBMS_OUTPUT.PUT_LINE(Iteration =' || counter);5 end loop;6 DBMS_OUTPUT.PUT_LINE('End');7 end;

BeginningIteration = 1Iteration = 2Iteration = 3Iteration = 4Iteration = 5End

4

Page 5: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Exception

DECLARE v_student_id NUMBER := &sv_student_id; v_name VARCHAR2(30);BEGIN SELECT RTRIM(first_name)||' '||RTRIM(last_name) INTO v_name FROM student WHERE student_id = v_student_id;

DBMS_OUTPUT.PUT_LINE ('Student name is '||v_name);EXCEPTION WHEN NO_DATA_FOUND THEN DBMS_OUTPUT.PUT_LINE ('There is no such student');END;In this example, you display the student's name on the screen. If there is no record in the STUDENT table corresponding to the value of v_student_id provided by the user, the exception NO_DATA_FOUND is raised. Therefore, you can say that the exception NO_DATA_FOUND covers this block, or this block is the scope of this exception. In other words, the scope of an exception is the portion of the block that is covered by this exception.

5

Page 6: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

RAISE_APPLICATION_ERROR is a special built-in procedure provided by Oracle. This procedure allows programmers to create meaningful error messages for a specific application. The RAISE_APLICATION_ERROR procedure works with user-defined exceptions. The syntax of the RAISE_APPLICATION_ERROR is

RAISE_APPLICATION_ERROR(error_number, error_message);orRAISE_APPLICATION_ERROR(error_number, error_message, keep_errors);As you can see, there are two forms of the RAISE_APPLICATION_ERROR procedure. The first form contains only two parameters: error_number and error_message. The error_number is a number of the error that a programmer associates with a specific error message, and can be any number between -20,999 and -20,000. The error_message is the text of the error, and it can contain up to 512 characters.

The second form of RAISE_APPLICATION_ERROR contains one additional parameter: keep_errors. Keep_errors is an optional Boolean parameter. If keep_errors is set to TRUE, the new error will be added to the list of errors that has been raised already. If keep_errors is set to FALSE, the new error replaces the list of errors that has been raised already. The default value for the parameter keep_errors is FALSE.It is important for you to note that the RAISE_APPLICATION_ERROR procedure works with unnamed user-defined exceptions. It associates the number of the error with the text of the error. Therefore, the user-defined exception does not have a name associated with it.

6

Page 7: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

DECLARE v_student_id STUDENT.STUDENT_ID%TYPE := &sv_student_id; v_total_courses NUMBER; e_invalid_id EXCEPTION;BEGIN IF v_student_id < 0 THEN RAISE e_invalid_id; ELSE SELECT COUNT(*) INTO v_total_courses FROM enrollment WHERE student_id = v_student_id; DBMS_OUTPUT.PUT_LINE ('The student is registered for '||v_total_courses||' courses'); END IF; DBMS_OUTPUT.PUT_LINE ('No exception has been raised');EXCEPTION WHEN e_invalid_id THEN DBMS_OUTPUT.PUT_LINE ('An id cannot be negative');END;

The RAISE_APPLICATION_ERROR procedure allows programmers to return error messages in a manner that is consistent with Oracle errors. However, it is important for you to note that it is up to a programmer to maintain the relationship between the error numbers and the error messages. For example, you have designed an application to maintain the enrollment information on students. In this application you have associated the error text "This ID is invalid" with the error number ORA-20001. This error message can be used by your application for any invalid ID. Once you have associated the error number (ORA-20001) with a specific error message (This ID is invalid), you should not assign this error number to another error message. If you do not maintain the relationship between error numbers and error messages, the error-handling interface of your application might become very confusing to the users and to yourself.

7

Page 8: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Exceptions typesa) standartd (NOT_LOGGED_ON, ZERO_DIVIDE, NO_DATA_FOUND,

INVALID_NUMBER, INVALID_CURSOR, TOO_MENY_ROWS, …);

b) user defined.

Standard exceptionsORA-1476 ZERO_DIVIDEORA-1012 NOT_LOGGED-ONORA-1403 NO_DATA_FOUNDORA-1001 INVALID_CURSORORA-6502 VALUE_ERRORORA-1422 TOO_MANY_ROWSORA-1017 LOGIN_DENIED

WHEN OTHERS THEN

m_error_code := SQLCODE;

m_error_text : = SUBSTR ( SQLERRM, 1, ...);

SQLERRM (error code)

8

Page 9: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Anonymous block

Tabulas izveidošana:create table FIRMAS (

NUMURS number Primary key,NOSAUKUMS varchar2(50),DIBIN_DATUMS date);

Datu ievade tabulā FIRMAS:insert into FIRMAS values(1, 'Venta', TO_DATE('21.08.2008', 'DD.MM.YYYY'));insert into FIRMAS values(2, 'Daugava', TO_DATE('18.11.2009', 'DD.MM.YYYY'));insert into FIRMAS values(3, 'Gauja', TO_DATE('11.12.2011', 'DD.MM.YYYY'));

Servera bufera darbības aktivēšana:set serveroutput on size 100000;

Anonīmā bloka programma:declare

num FIRMAS.NUMURS%TYPE;nos FIRMAS.NOSAUKUMS%TYPE;dat FIRMAS.DIBIN_DATUMS%TYPE;

type RAKSTA_TIPS is record ( elem_1 FIRMAS.NUMURS%TYPE, elem_2 FIRMAS.NOSAUKUMS%TYPE, elem_3 FIRMAS.DIBIN_DATUMS%TYPE); raksts_1 RAKSTA_TIPS;begin

SELECT A.* INTO raksts_1FROM FIRMAS A WHERE A.NUMURS = 2;DBMS_OUTPUT.PUT_LINE('Firmas dati:');DBMS_OUTPUT.PUT_LINE('Numurs: ' || raksts_1.elem_1);DBMS_OUTPUT.PUT_LINE('Nosaukums: ' || raksts_1.elem_2);DBMS_OUTPUT.PUT_LINE('Dibināšanas datums: ' || raksts_1.elem_3);

end;

Firmas dati:Numurs: 2Nosaukums: DaugavaDibināšanas datums: 2009.11.18PL/SQL procedure successfully completed.

9

Page 10: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

PL/SQL procedureA procedure is a module performing one or more actions; it does not need to return any values. The syntax for creating a procedure is as follows:

CREATE OR REPLACE PROCEDURE name [(parameter[, parameter, ...])]AS [local declarations]BEGIN executable statements[EXCEPTION exception handlers]END [name];

A procedure may have 0 to many parameters. This will be covered in the next lab. Every procedure has two parts: (1) the header portion, which comes before AS (sometimes you will see IS—they are interchangeable), keyword (this contains the procedure name and the parameter list), and (2) the body, which is everything after the IS keyword. The word REPLACE is optional. When the word REPLACE is not used in the header of the procedure, in order to change the code in the procedure, the procedure must be dropped first and then re-created. Since it is very common to change the code of the procedure, especially when it is under development, it is strongly recommended to use the OR REPLACE option.

10

Page 11: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Example

create or replace procedure F_COUNT(count OUT number) iscursor CURSOR_A isselect * from FIRMS;

begin for m_row in CURSOR_A loop

skaits := CURSOR_A%ROWCOUNT; exit;end loop;

end;

declarem1 number default 0;

beginF_COUNT(m1);

DBMS_OUTPUT.PUT_LINE('Count = ' || m1);end;

Count = 3

FIRMSF_NUM

F_NAM CRE_DAT

1 BBB 2005-FEB-152 CCC 2006-JAN-233 AAA 2007-DEC-6

11

Page 12: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Example of PL/SQL procedure

create or replace procedure PREMIJAS_APREKINS(raksts_1 IN TABULA_DARBINIEKI%rowtype,

premija IN OUT TABULA_DARBINIEKI.ALGA%type) IS kluda_premija EXCEPTION; - - īpašās situācijas definējumsbegin if raksts_1.ALGA is NULL then raise kluda_premija; else premija := raksts_1.ALGA * 0.05; end if; if raksts_1.pielikumi IS NOT NULL THEN premija := premija + raksts_1.pielikumi*0.15; end if; DBMS_OUTPUT.PUT_LINE('prēmija' || raksts_1.uzvards_vards || TOCHAR(premija));exception when kluda_premija THEN premija := 0; DBMS_OUTPUT.PUT_LINE('Nav prēmija' || raksts_1.uzvards_vards);end;

12

Page 13: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

PL/SQL functionsFunctions are another type of stored code and are very similar to procedures. The significant difference is that a function is a PL/SQL block that returns a single value. Functions can accept one, many, or no parameters, but a function must have a return clause in the executable section of the function. The datatype of the return value must be declared in the header of the function. A function is not a stand-alone executable in the way that a procedure is: It must be used in some context. You can think of it as a sentence fragment. A function has output that needs to be assigned to a variable, or it can be used in a SELECT statement.

CREATE [OR REPLACE] FUNCTION function_name (parameter list) RETURN datatypeISBEGIN <body> RETURN (return_value);END;

The function does not necessarily have any parameters, but it must have a RETURN value declared in the header, and it must return values for all the varying possible execution streams. The RETURN statement does not have to appear as the last line of the main execution section, and there may be more than one RETURN statement (there should be a RETURN statement for each exception). A function may have IN, OUT, or IN OUT parameters, but you rarely see anything except IN parameters since it is bad programming practice to do otherwise.

create or replace function Function_name ( parameter_1 [IN vai OUT vai IN OUT] parameter_type, parameter _2 [IN vai OUT vai IN OUT] parameter_type, … ) RETURN type IS || ASbody ; -- PL/SQL block

13

Page 14: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Example of PL/SQL function

create or replace function F_DATA(f_number IN number) return FIRMS%rowtype is

cursor CURSOR_A(num number) isselect * from FIRMS where F_NUM = num;m_row FIRMAS%rowtype;

beginopen CURSOR_A(f_numurs);

fetch CURSOR_A into m_row;close CURSOR_A;return m_row;

end;

declarem1 number;row FIRMS%rowtype;m_nam FIRMS.F_NOS%type;m_dat FIRMS.CRE_DAT%type;

beginm1 := 2;raksts := F_DATA(m1);m_nos := row.F_NOS;m_dat := row.CRE_DAT;DBMS_OUTPUT.PUT_LINE('Firm data = ' || m_nam || ' ' || m_dat);

end;

Firm data = CCC 23-JAN-06

FIRMSF_NUM

F_NAM CRE_DAT

1 BBB 2005-FEB-152 CCC 2006-JAN-233 AAA 2007-DEC-6

14

Page 15: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Example of PL/SQL function

create or replace function FUNKCIJA_1 (parametrs_1 Viesi.UZV%TYPE,parametrs_2 Viesi.UZV%TYPE,parametrs_3 NUMBER ) RETURN BOOLEAN ISmainīgais_1 NUMBER;mainīgais_2 CONSTANT NUMBER := 70;f_mainīgais BOOLEAN;main_1 Viesi.UZV%TYPE;main_2 Viesi.VAR%TYPE;main_3 Viesi.ALGA%TYPE;

begin- - Komentārsselect UZV,VAR, ALGA INTO main_1, main_2, main_3from Viesiwhere UZV = parametrs_1 AND VAR = parametrs_2;if main_3 >= 200 then f_mainīgais := TRUE; else f_mainīgais := FALSE;end if;

return f_mainīgais;end FUNKCIJA_1;

15

Page 16: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Local or nested Modules

A local or nested module is a procedure or function that is defined in the declaration section of a PL/SQL block (anonymous or named). This module is considered local because it is defined only within the parent PL/SQL block. It cannot be called by any other PL/SQL blocks defined outside that enclosing block. Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly invoke any local procedures or functions.

The syntax for defining the procedure or function is exactly the same as that used for creating standalone modules. The following anonymous block, for example, declares a local procedure:

DECLARE PROCEDURE show_date (date_in IN DATE) IS BEGIN DBMS_OUTPUT.PUT_LINE (TO_CHAR (date_in, 'Month DD, YYYY'); END show_date;

BEGIN ... END ;

Local modules must be located after all of the other declaration statements in the declaration section. You must declare your variables, cursors, exceptions, types, records, tables, and so on before you type in the first PROCEDURE or FUNCTION keyword.

16

Page 17: PL/SQL valodas procedūras Web viewThe word REPLACE is ... Figure shows how blocks that are external to a procedure definition cannot “cross the line” into the procedure to directly

Benefits of Local Modularization

There are two central reasons to create local modules: 1) To reduce the size of the module by stripping it of repetitive code.

This is the most common motivation to create a local module; you can see its impact in the next example. The code reduction leads to higher code quality because you have fewer lines to test and fewer potential bugs. It takes less effort to maintain the code because there is less to maintain. And when you do have to make a change, you make it in one place in the local module, and the effects are felt immediately throughout the parent module.

2) To improve the readability of your code. Even if you do not repeat sections of code within a module, you still may want to pull out a set of related statements and package them into a local module. This can make it easier to follow the logic of the main body of the parent module.

17