CREATING STORED PROCEDURES AND FUNCTIONS. Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous.

Slides:



Advertisements
Similar presentations
Sub and Function Procedures
Advertisements

Spring Semester 2013 Lecture 5
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions.
Oracle PL/SQL IV Exceptions Packages.
PL/SQL.
JavaScript Part for Repetition Statement for statement Cpecifies each of the items needed for counter-controlled repetition with a control variable.
VBA Modules, Functions, Variables, and Constants
1 Copyright © 2004, Oracle. All rights reserved. Creating Stored Procedures.
9 Copyright © 2009, Oracle. All rights reserved. Introducing Stored Procedures and Functions.
Introduction to Methods
Bordoloi and Bock PROCEDURES, FUNCTIONS & TRIGGERS.
Dr. James Dullea, CSC8490 Introduction to PL/SQLSlide 1 of 36 7From Prof. Dullea CSC8490 Introduction to PL/SQL Module 01-9 Revised: June 12, 2005 Dr.
Advanced Databases Advanced PL/SQL Programming: Procedure, Function and Package.
PL / SQL P rocedural L anguage / S tructured Q uery L anguage Chapter 7 in Lab Reference.
Bordoloi and Bock EXCEPTIONS. Bordoloi and Bock Errors Two types of errors can be found in a program: compilation errors and runtime errors. There is.
Stored Procedures Functions Packages
 Allows sophisticated data processing  Build complex business logic in a modular fashion  Use over and over  Execute rapidly – little network traffic.
 Allows sophisticated data processing  Build complex business logic in a modular fashion  Use over and over  Execute rapidly – little network traffic.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 7 PL/SQL Packages.
1 Procedures Blocks of code which can be called from anywhere in a program Enable us to avoid needless repetition of the same code Can take parameters.
INTRODUCTION TO PL/SQL. Class Agenda Introduction Introduction to PL/SQL Declaring PL/SQL Variable Creating the Executable Section Interacting with the.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
PL/SQLPL/SQL Oracle10g Developer: PL/SQL Programming Chapter 6 Functions.
Overview · What is PL/SQL · Advantages of PL/SQL · Basic Structure of a PL/SQL Block · Procedure · Function · Anonymous Block · Types of Block · Declaring.
Lecture 8 Creating Stored Functions. Objectives  After completing this lesson, you should be able to do the following:  What is Function?  Types of.
CpSc 462/662: Database Management Systems (DBMS) (TEXNH Approach) Stored Procedure James Wang.
PL / SQL By Mohammed Baihan. What is PL/SQL? PL/SQL stands for Procedural Language extension of SQL. PL/SQL is a combination of SQL along with the procedural.
1 Copyright © 2004, Oracle. All rights reserved. Introduction to PL/SQL.
Chapter 15 Introduction to PL/SQL. Chapter Objectives  Explain the benefits of using PL/SQL blocks versus several SQL statements  Identify the sections.
PL/SQL. Introduction to PL/SQL block Declare declarations Begin executable statement Exception exception handlers End;
Database Application Development using PL/SQL Programming.
Procedural programming in Java Methods, parameters and return values.
Bordoloi and Bock Control Structures: Iterative Control.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
Stored Procedures. Definition a stored procedure is a set of Structured Query Language (SQL) statements with an assigned name that's stored in the database.
Chapter 9: Advanced SQL and PL/SQL Guide to Oracle 10g.
implicit and an explicit cursor
Handling Exceptions. Objectives What is exception Types of exceptions How to handle exceptions Trapping pre defined oracle errors.
Passing Parameters. 2 home back first prev next last What Will I Learn? List the types of parameter modes Create a procedure that passes parameters Identify.
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.
PRACTICE OVERVIEW PL/SQL Part Your stored procedure, GET_BUDGET, has a logic problem and must be modified. The script that contains the procedure.
Oracle10g Developer: PL/SQL Programming1 Objectives Named program units How to identify parameters The CREATE PROCEDURE statement Creating a procedure.
Creating Procedures. PL/SQL Program Construct Tools Constructs Anonymous Block Application procedures or functions Application packages Application Triggers.
Text TCS INTERNAL Oracle PL/SQL – Introduction. TCS INTERNAL PL SQL Introduction PLSQL means Procedural Language extension of SQL. PLSQL is a database.
Oracle9i Developer: PL/SQL Programming Chapter 5 Functions.
Lab 2 Writing PL/SQL Blocks CISB514 Advanced Database Systems.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
Programming Fundamentals Enumerations and Functions.
Kingdom of Saudi Arabia Ministry of Higher Education Al-Imam Muhammad Ibn Saud Islamic University College of Computer and Information Sciences Overview.
Introduction to PL/SQL N. Dimililer. About PL/SQL –PL/SQL is an extension to SQL with design features of programming languages. –Data manipulation and.
Stored Procedures and Functions Pemrograman Basis Data MI2183.
9 Copyright © 2007, Oracle. All rights reserved. Creating Stored Procedures and Functions.
Oracle9i Developer: PL/SQL Programming Chapter 6 PL/SQL Packages.
1 Copyright © 2004, Oracle. All rights reserved. PL/SQL Programming Concepts: Review.
User-Written Functions
Oracle11g: PL/SQL Programming Chapter 5 Procedures.
Creating Stored Procedures and Functions
Difference between Oracle PL/SQL and MySQL
PL/SQL.
UNIT - V STORED PROCEDURE.
Handling Exceptions.
PL/SQL Scripting in Oracle:
Oracle Stored Procedures and Functions
PRACTICE OVERVIEW PL/SQL Part - 2.
Handling Exceptions.
Procedures Organized by Farrokh Alemi, Ph.D. Narrated by Yara Alemi
PL/SQL Declaring Variables.
Oracle Stored Procedures and Functions
Presentation transcript:

CREATING STORED PROCEDURES AND FUNCTIONS

Objectives After completing this lecture, you should be able to do the following: Differentiate between anonymous blocks and subprograms Create a simple procedure and invoke it from an anonymous block Create a simple function Create a simple function that accepts a parameter Differentiate between procedures and functions

Procedures and Functions  Are named PL/SQL blocks.  Are called PL/SQL subprograms.  Have block structures similar to anonymous blocks:  Optional declarative section (without DECLARE keyword).  Mandatory executable section.  Optional section to handle exceptions.

Differences Between Anonymous Blocks and Subprograms

Procedure, function  Procedure  A program that performs one or more actions and is called as an executable PL/SQL statement.  You can pass information into and out of a procedure through its parameter list.  Function  A program that returns a single value and is used just like a PL/ SQL expression.  You can pass information into a function through its parameter list.

Procedure  A procedure is a module that performs one or more actions.  Because a procedure call is a standalone executable statement in PL/SQL, a PL/SQL block could consist of nothing more than a single call to a procedure.

Procedure: Syntax

Cont.

Syntax CREATE [OR REPLACE] PROCEDURE procedure name [(parameter [{IN | OUT | IN OUT}] type,...., parameter [{IN | OUT | IN OUT}] type)] AS [local_variable_declarations] BEGIN procedure_body; END procedure name;

Calling a Procedure  A procedure is called as an executable PL/SQL statement. In other words, a call to a procedure must end with a semicolon (;) and be executed before and after other SQL or PL/SQL statements (if they exist) in the execution section of a PL/SQL block.  The following executable statement runs the apply_discount procedure: BEGIN apply_discount( new_company_id, 0.15 ); -- 15% discount END;

Calling a Procedure  If the procedure does not have any parameters, then you call the procedure without any parentheses: display_store_summary;  In Oracle8i Database and later, you can also include empty open and close parentheses as well, as in: display_store_summary();  A programmer does not need to know about the inside of the procedure (the body)to be able to call it properly from another program.  The header for the apply_discount procedure mentioned in the previous section is: PROCEDURE apply_discount (company_id_in IN company.company_id%TYPE, discount_in IN NUMBER) It consists of the module type, the name, and a list of two parameters.

Calling a Procedure  The Procedure Header is The portion of the procedure definition that comes before the IS keyword.  The header provides all the information a programmer needs to call that procedure, namely: The procedure name. The parameter list, if any.

Calling a Procedure  In the Procedure Header, The word REPLACE is optional.  When REPLACE is not used in the header of the procedure, to change the code in the procedure, you must drop and then re-create the procedure. Because it is very common to change a procedure’s code, especially when it is under development.  it is strongly recommended that you use the OR REPLACE option.

Calling a Procedure  The Procedure Body is the code required to implement that procedure, and consists of the declaration, execution, and exception sections of the procedure.  Everything after the IS keyword in the procedure makes up that procedure’s body.  The exception and declaration sections are optional. If you have no exception handlers, leave off the EXCEPTION keyword and simply enter the END statement to terminate the procedure.  If you have no declarations, the BEGIN statement simply follows immediately after the IS keyword.  You must supply at least one executable statement in a procedure.

Calling a Procedure  The END Descriptor, You can append the name of the procedure directly after the END keyword when you complete your procedure, as shown here: PROCEDURE display_stores (region_in IN VARCHAR2) IS BEGIN... END display_stores;  This name serves as a label that explicitly links the end of the program with its beginning.  You should, as a matter of habit, use an END descriptor.

Procedure: Example

Invoking (Calling) the Procedure

Stored procedure parameters We can pass parameters to procedures in three ways: 1) IN-parameters. 2) OUT-parameters. 3) IN OUT-parameters.

Stored procedure CREATE PROCEDURE HELLO IS BEGIN DBMS_OUTPUT.PUT_LINE(’Hello World’); END; The above declares a HELLO procedure that just displays ’Hello World’. You can run it as part of a code fragment, or inside other procedures (or functions). For example: BEGIN HELLO(); END; Or you can simply execute it in SQL*Plus by typing: CALL HELLO();

Stored procedure Would setup some procedure to accept an INT variable named N. Writing a simple procedure to display a variable name, you can come up with something like this: CREATE PROCEDURE DISPN (N INT) IS BEGIN DBMS_OUTPUT.PUT_LINE(’N is ’ || N); END; Which if you call, will promptly display: SQL> CALL DISPN( ); N is OR begin DISPN( ); end; /

Stored procedure  You can also have multiple parameters. For example, you can accept A and B and display their sum and product. CREATE OR REPLACE PROCEDURE DISP_AB (A INT, B INT) IS BEGIN DBMS_OUTPUT.PUT_LINE(’A + B = ’ || (A + B)); DBMS_OUTPUT.PUT_LINE(’A * B = ’ || (A * B)); END; Which when ran, displays something like (depending on the values you provide): SQL> CALL DISP_AB(17,23); A + B = 40 A * B = 391

Stored procedure  it should be noted that you can use any PL/SQL type as an argument. For example, VARCHAR2 and others are perfectly acceptable. For example: CREATE OR REPLACE PROCEDURE DISP_NAME (NAME VARCHAR2) IS BEGIN DBMS_OUTPUT.PUT_LINE(’Hi ’ || NAME || ’!’); END; Which when called displays: SQL> CALL DISP_NAME(’Amal’); Hi Amal!

Stored procedure  We’ve only been giving the procedure data via parameters. This is the default (IN). What we could also do is get data from the procedure, via an OUT parameter. To do that, we simply specify OUT in between the parameter name and its type. For example: CREATE OR REPLACE PROCEDURE SUM_AB (A INT, B INT, C OUT INT) IS BEGIN C := A + B; END;  Notice that the above code does not display the resulting sum, it just changes the value of the C parameter.  Also notice the word OUT right after the declaration of C parameter name.

Cont, we will use a code fragment to call the procedure: DECLARE R INT; BEGIN SUM_AB(23,29,R); DBMS_OUTPUT.PUT_LINE(’SUM IS: ’ || R); END; Which when ran, displays: SUM IS: 52

Example ( IN OUT ) CREATE OR REPLACE PROCEDURE squareNum(x IN OUT number) IS BEGIN x := x * x; END squareNum; DECLARE a number; BEGIN a:= 23; squareNum(a); dbms_output.put_line(' Square of (23): ' || a); END; /

Dropping Procedures  If you’re interested in getting rid of a procedure totally, you can DROP it. The general format of a DROP is: DROP PROCEDURE procedure_name;

Function  A function is a module that returns a value. Unlike a procedure call, which is a standalone executable statement, a call to a function can exist only as part of an executable statement, such as an element in an expression or the value assigned as the default in a declaration of a variable.  Because a function returns a value, it is said to have a data type. A function can be used in place of an expression in a PL/SQL statement having the same data type as the function.

Function: Syntax

The Function Header The function header : is the portion of the function definition that comes before the IS keyword.  The header provides all the information a programmer needs to call that function, namely: The function name. The parameter list, if any. The RETURN datatype. A programmer should not need to look at the inside of the function (its body) in order to be able to call it properly from another program.

The Function Body  The body of the function: is the code required to implement the function.  It consists of the declaration, execution, and exception sections of the function. Everything after the IS keyword in the function makes up that function’s body.  Once again, the declaration and exception sections are optional.  If you have no exception handlers, simply leave off the EXCEPTION keyword and enter the END statement to terminate the function.  If you have no declarations, the BEGIN statement simply follows immediately after the IS keyword.  A function’s execution section should have a RETURN statement in it.  If, however, your function finishes executing without processing a RETURN statement, Oracle will raise the following error : ORA-06503: PL/SQL: Function returned without value.

The RETURN Statement  A function must have at least one RETURN statement in its execution section of statements.  It can have more than one RETURN, but only one is executed each time the function is called.  The RETURN statement that is executed by the function determines the value that is returned by that function.  When a RETURN statement is processed, the function terminates immediately and returns control to the calling PL/SQL block.  The RETURN clause in the header of the function is different from the RETURN statement in the execution section of the body.  While the RETURN clause indicates the datatype of the return or result value of the function, the RETURN statement specifies the actual value that is returned.  You have to specify the RETURN datatype in the header, but then also include at least one RETURN statement in the function.  The datatype indicated in the RETURN clause in the header must be compatible with the datatype of the returned expression in the RETURN statement.

The END Descriptor  You can append the name of the function directly after the END keyword when you complete your function, as shown here: FUNCTION tot_sales (company_in IN INTEGER) RETURN NUMBER IS BEGIN... END tot_sales;  This name serves as a label that explicitly links the end of the program with its beginning.  You should, as a matter of habit, use an END descriptor.

Calling a Function A function is called as part of an executable PL/SQL statement wherever an expression can be used.

Assign the default value of a variable Assign the default value of a variable with a function call: DECLARE v_nickname VARCHAR2(100) := favorite_nickname ('Steven');

Functions Without Parameters If a function has no parameters, the function call is written without parentheses.

The RETURN Datatype  A PL/SQL function can return virtually any kind of data known to PL/SQL, from scalars (single, primitive values like dates and strings) to complex structures such as collections, object types, cursor variables, and LOBs.  You may not, however, return an exception through a function, because in PL/SQL, exceptions do not have a type.

Function: Example

Invoking the Function

Passing Parameter to the Function

Invoking the Function with a Parameter

Example procedure CREATE OR REPLACE PROCEDURE greetings AS BEGIN dbms_output.put_line('Hello World!'); END; / BEGIN greetings; END; /

Example Function CREATE or replace function Sumnum (N number, M number) RETURN number IS BEGIN RETURN N+M; END Sumnum; / set serveroutput on BEGIn dbms_output.put_line('The sum is '||Sumnum(2,2)); END ; /

Summary In this lecture, you should have learned how to: Create a simple procedure Invoke the procedure from an anonymous block Create a simple function Create a simple function that accepts parameters Invoke the function from an anonymous block