Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to PL/SQL Procedures & Cursors

Similar presentations


Presentation on theme: "Introduction to PL/SQL Procedures & Cursors"— Presentation transcript:

1 Introduction to PL/SQL Procedures & Cursors
Lecture 4 Introduction to PL/SQL Procedures & Cursors

2 Overview Overview of PL/SQL Development of a coded block
Interacting with an Oracle Database Controlling PL/SQL process flow Cursor handling

3 Embedding SQL SQL is not functionally complete
Lacks the full facilities of a programming language variables, flow of control etc. All DBMSs top up functionality by embedding SQL in a procedural language But details vary from one DBMS to another. However, procedures and functions can be ported between systems.

4 PL/SQL - Introduction An Oracle-specific procedural extension to SQL, allowing for modularity, variable declaration, loops and logical constructs. Allows for advanced error handling. Communicates natively with other Oracle database objects. Managed centrally within the Oracle database. PL/SQL is a special language available for developers to code stored procedures which are integrated seamlessly with the database objects via SQL. The language, however, has far more potential than the simple commands of SQL (UPDATE, SELECT, INSERT & DELETE). The language allows for modularity and complexity of standard procedural languages. Loops and variables are permitted within this language which makes if far more useful for data extraction and manipulation than the standard SQL. PL/SQL is used to enforce the logic and business rules of the database application. It is a simple language which has all the logic constructs of a programming language and the advantage of a robust error handling system which is not common in other procedural languages. The modularization of code is another advantage to the language and allows for the re-use of code once created in a procedure. PL/SQL is the only programming language which will natively interact with a Oracle database and within the database environment. The language is managed centrally within the database and the DBA manages the source code and execution privileges in the same way as they manage other database objects. Once a procedure has been created is is treated the same way as other DB objects.

5 The main disadvantage of a client/server application is the difficulty in maintaining the business rules for an application. The middle layer of Oracle application logic means that the business rules are no longer decentralised throughout the application. The data is validated etc. before being written to the database i.e.: data is entered via the client end …. The business rules are applied ….. The data is written to the database. This gives the advantage that the code is centrally managed by the DBA of a system, this is where the authority to access a procedure by a user or object is granted, it also means that any changes to either business rules or authorities are managed in one place making the system more robust. Once a procedure has been complied that change is automatically available to those who have authority to view or access that procedure. On business systems where the logic is stored on the client end of the application the change will have to be reflected throughout the distributed system. The risk of a system being missed is reduced. PL/SQL procedures are all stored on the central database, they are processed on the server not the client, one change to the procedure is all that is needed rather than the change having to be reflected on every client. Also because the procedure is performed on the server the processing time is server dependent not client (ie better) Triggers on tables etc. will be coded in PL/SQL which gives them more power the code is also easy to read and therefore debugging the code or maintaining the code for other developers or DBA is more straight forward (this does not mean that the developer can reduce the number of comments within the code !). If an interface is used and Oracle forms is used then PL/SQL may be used to interface between the client and the database. This is the same as coding in the “middle layer” of the system and is a way of ensuring that the data is correct prior to being written to the database. “Database-centric client/server application” this basically is the same as the first point but it’s a fancy way of saying it :O) Why use PL/SQL? Manage business rules – through middle layer application logic. Generate code for triggers. Generate code for the user interface. Enable database-centric client/server applications.

6 Centralised vs. Decentralised
Multiple copies of executable code on the decentralised system – multiple copies to maintain leading to increase difficulty in maintaining the system Begin : End; Server Begin : End; Server Common copy of executed code – one copy to maintain

7 Advantages of using PL/SQL to access Oracle
PL/SQL is managed centrally within the database. Code is managed by the DBA, and execution privileges are managed in the same way as with other objects. PL/SQL objects are first-class Oracle DB objects. Easy to read: with modularity features and error handling.

8 Centralised Control Enables the DBA to:
specify rules in one place (as a procedure, function, trigger or package in PL/SQL); force user access through the predefined PL/SQL, so users cannot write their own procedural code and use this instead e.g. define security privileges giving users access to table(s) only through a particular procedure.

9 Using PL/SQL as a Programming Language
Permits all “flow of control” operations of standard programming languages, e.g. Jumps GOTO Conditions IF-THEN-END IF; IF-THEN-ELSE-END IF Loops LOOP-EXIT; WHEN-END LOOP; FOR-END LOOP; WHILE-END LOOP Allows extraction of data into variables and its subsequent manipulation.

10 Modules in PL/SQL There are 4 types of modules in PL/SQL
Procedure – a series of statements which may or may not return a value. Function – a series of statements which must return a single value. Trigger – a series of statements which is executed after an event has triggered a condition. Package – a collection of procedures and functions which has 2 parts: a listing and a body. Due to the amount of time available on this unit we will not be going into significant detail on the available modules. However in order to do cursors it is necessary to select on type of module an concentrate on that one. We will be focusing on procedures but it is important to be aware of the others. The main difference between a function and a procedure is the return value option. A procedure does not have to return a value to the code or module which called it where as a function must. Both types of modules may have parameters passed to them from other components and these may be used in order for the code contained to be processed. Triggers have been covered in previous sessions and therefore do not require further expansion here, suffice to note that the trigger will be activated by an execution event such as select, update, insert or delete. A package is a complex module within the database and is powerful when used effectively. A package will contain a list of all functions and procedures which are utilised by it and then a separate module will contain the package body. The body will actually contain the code for the functions and procedures. There is not enough time to go into this module in sufficient detail and at this level it is sufficient to be aware of the different modules and there different natures.

11 Use of Data Types Number – used to store any number.
Char(size) & varchar2(size) e.g. char(10) – used to store alphanumerical text strings; the char data type will pad the value stored to the full length declared. Date – used to store dates and times. Long – used to store large blocks of text up to 2 gigabytes in length (limited operations) PL/SQL offers great flexibility in variable declaration. There are several data types that can be used in PL/SQL that correspond to the datatypes used on the database these are detailed on the next 2 slides. You should be aware of them but will not be expected to know them all. The ones above are the most common used. The aim of these following slides is to illustrate to you the flexibility of the datatypes available and to give a brief description of what each datatype if for so that if you see code in books you will have a better understanding of what it being stored in the database.

12 Non-DB Data Types DEC, DECIMAL, REAL, INTEGER, INT – these are numerical data types that are a subset of number. Binary_integer – binary format for number type but can not be stored in database unless converted first. Character – same as char. Boolean – true/false value. Table/record – tables can be used to store the equivalent of an array while records store the variables with composite data types. These data types are used in PL/SQL but are not designed for use in storing data to a table. What this means is that you can declare a variable as datatype detailed above but this datatype can not be used when creating a table. The reason that this would be done is if the datatype in the variable gives greater flexibility that that in the table declaration. For example there is greater flexibility in the declaration of the numeric datatypes than the simple declaration of number. Again this is intended to illustrate the flexibility of PL/SQL.

13 SQL Scripts A set of commands to run in sequence.
Stored as a text file (e.g. using Notepad) on disk and not in the data dictionary. It is accessed by its file name or Start. Script called: Create_lecturer_copy.sql Executed by:

14 The SQL Procedure A block of SQL statements stored in the Data Dictionary and called by applications. Satisfies frequently-used or critical application logic. When called, all code within the procedure is executed (unlike packages). Action takes place on the server, not the client. Does not (normally) return a value to the calling program. Not available in Oracle 6 or older. Aids security as DBA may grant access to procedures rather than tables, therefore some users cannot access tables except through a procedure.

15 Building a Procedure: Contents
CREATE OR REPLACE command; Object to be created; Name of object; Any variables accessed or imported; Local variables declared; Code block enclosed by BEGIN … END;

16 Create or replace command Object to be created
Name of object Any variables accessed or imported Declared local variables Code This procedure is called inflation_rise and uses a variable accessed as inf_rate which is a number, this is passed in when the procedure is used. It simply updates the salary by the rate of inflation. Create or replace procedure inflation_rise (inf_rate in number) Begin update employee set salary = salary + (salary * inf_rate / 100); commit; End;

17 Compiling and Executing Procedures
Like any program the code needs to be compiled. @inflation_rise compiles the procedure from a file with this name; makes it available to the data base. Execute inflation_rise executes the procedure. Remember to re-compile a procedure after editing. For ease of use, it is best to write procedures in Notepad, then they can be easily edited and you have a back-up copy.

18 Example Local variable used by procedure
CREATE OR REPLACE PROCEDURE validate_customer (v_cust VARCHAR) AS v_count NUMBER; BEGIN SELECT COUNT(*) INTO v_count FROM CUSTOMER WHERE CUST_CODE = v_cust; IF v_count > 0 THEN DBMS_OUTPUT.PUT_LINE(‘customer valid’); ELSE DBMS_OUTPUT.PUT_LINE(‘customer not recognised’); END IF; END; Variable passed into procedure Local variable used by procedure SQL Code Block

19 Cursors in SQL Enables users to loop round a selection of data.
Stores data select from a query in a temp area for use when opened. Use complex actions which would not be feasible in standard SQL selection queries

20 Declaring Cursors Declared as a variable in the same way as standard variables. Identified as cursor type. SQL included, e.g. Cursor cur_emp is Select emp_id, surname ‘name’, grade, salary From employee Where regrade is true;

21 Cursors A cursor is a temporary store of data.
The data is populated when the cursor is opened. Once opened, the data must be moved from the temporary area to a local variable to be used by the program. These variables must be populated in the same order that the data is held in the cursor. The data set is looped round till an exit clause is reached.

22 Cursor Functions Active set 7369 SMITH CLERK 7566 JONES MANAGER
7788 SCOTT ANALYST 7876 ADAMS CLERK 7902 FORD ANALYST Current row Cursor

23 Controlling the Cursor
No DECLARE OPEN FETCH EMPTY? Yes CLOSE Create a named SQL area Identify the active set Load the current row into variables Test for existing rows Release the active set Return to FETCH if rows found

24 Controlling the Cursor… Fetch a row from the cursor.
Open the cursor. Pointer Cursor Fetch a row from the cursor. Cursor Pointer Continue until empty. Cursor Pointer Close the cursor. Cursor

25 Cursor Attributes To obtain status information about a cursor.
Attribute Type Description %ISOPEN Boolean Evaluates to TRUE if the cursor is open %NOTFOUND Boolean Evaluates to TRUE if the most recent fetch does not return a row %FOUND Boolean Evaluates to TRUE if the most recent fetch returns a row; logical complement of %NOTFOUND %ROWCOUNT Number Evaluates to the total number of rows returned so far

26 25463 12245 55983 12524 98543 Create or replace procedure proc_test as v_empid number; Cursor cur_sample is Select empid from employee where grade > 4; Begin open cur_sample; loop fetch cur_sample into v_empid; exit when cur_sample%notfound; update employee set salary = salary + 500 where empid = v_empid; end loop; End; Data returned by cursor Declare Cursor Open cursor for use. Loops round each value returned by the cursor Place the value from the cursor into the variable v_empid Stop when no more records are found

27 Notepad file called: Create_procedures.sql 1) Open SQL*Plus and logon
2) At the prompt enter: @create_procedures You will get a prompt which should say ‘procedure created’ otherwise use SHOW ERRORS to view errors in the code. 3) To run the procedure enter: Execute proc_test 4) If you check your data you should now find that the procedure has run successfully

28 Use of conditions IF statements can be used E.g.
If <condition> Then ….. End if; E.g. Remember to end the IF statement Use of indented code will make it easier to debug! . . . IF v_ename = 'MILLER' THEN v_job := 'SALESMAN'; v_deptno := 35; v_new_comm := sal * 0.20; END IF;

29 The %ISOPEN Attribute Can fetch rows only when the cursor is open.
Use the %ISOPEN cursor attribute before performing a fetch to test whether the cursor is open. Example IF NOT cur_sample%ISOPEN THEN OPEN cur_sample; END IF; LOOP FETCH cur_sample...

30 Cursors and Records Process the rows of the active set conveniently by fetching values into a PL/SQL RECORD. Example DECLARE CURSOR emp_cursor IS SELECT empno, ename FROM emp; emp_record emp_cursor%ROWTYPE; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO emp_record; ...

31 Cursor FOR Loops The cursor FOR loop is a shortcut to process cursors.
Syntax Implicitly opens, fetches, and closes cursor. The record is implicitly declared. FOR record_name IN cursor_name LOOP statement1; statement2; . . . END LOOP;

32 Cursor FOR Loops: An Example
Retrieve employees one by one until no more are left: DECLARE CURSOR emp_cursor IS SELECT ename, deptno FROM emp; BEGIN FOR emp_record IN emp_cursor LOOP -- implicit open and implicit fetch occur IF emp_record.deptno = 30 THEN ... END LOOP; -- implicit close occurs END;


Download ppt "Introduction to PL/SQL Procedures & Cursors"

Similar presentations


Ads by Google