SUBPROGRAM Procedures and Functions in Oracle SUBPROGRAM What is subprogram? A subprogram is a program unit/module that performs a particular task These subprograms are combined to form larger program[.]
Trang 1Procedures and
Functions in Oracle
Trang 2SUBPROGRAM
Trang 3What is subprogram?
A subprogram is a program unit/module that performs a particular
task These subprograms are combined to form larger programs This is basically called the ‘Modular design’ A subprogram can be invoked by another subprogram or program which is called the
calling program.
A subprogram can be created:
At the schema level
Inside a package
Inside a PL/SQL block
Trang 4What is subprogram?
At the schema level, subprogram is a standalone subprogram It is created with the CREATE PROCEDURE or the CREATE FUNCTION stored in the database and can be deleted with the DROP PROCEDURE or DROP FUNCTION statement
A subprogram created inside a package is a packaged subprogram It is stored in the database and can be deleted only when the package is
deleted with DROP PACKAGE statement
Trang 5PL/SQL subprograms
PL/SQL subprograms are named PL/SQL blocks that can be invoked with
a set of parameters PL/SQL provides two kinds of subprograms:
Functions – These subprograms return a single value; mainly
used to compute and return a value
Procedures – These subprograms do not return a value directly;
mainly used to perform an action
Trang 6Parts of a PL/SQL subprograms
Each PL/SQL subprogram has a name, and may also have a parameter list Also have the following three part
Trang 7to the subprogram and cease to exist when the subprogram completes execution.
Trang 8I Procedure
Procedure hay còn gọi là thủ tục.
Gom 1 nhóm lệnh SQL cùng xử lý 1 mục đích cụ thể.
Đặt cho nó 1 cái tên và khai báo tham số truyền vào để khi cần
sử dụng ta chỉ gọi tên và truyền tham số
Trang 9 Procedure là một khối độc lập của một chương trình có thể được lưu
trữ trong cơ sở dữ liệu.
Gọi đến các Procedure này có thể được thực hiện bằng cách đề cập
đến tên của chúng.
Nó chủ yếu được sử dụng để thực hiện một quá trình bên trong
PL/SQL.
Nó có thể có khối lồng nhau, hoặc nó có thể được xác định và lồng
vào bên trong các khối hoặc các gói khác.
Nó chứa một phần khai báo (tùy chọn), phần thực thi, phần xử lý
ngoại lệ (tùy chọn).
Các giá trị có thể được thông qua vào các thủ tục hoặc lấy từ các thủ
tục thông qua các tham số.
Những thông số cần được đưa vào khai báo để sử dụng.
Procedure có thể có RETURN để trả lại quyền kiểm soát vào khối gọi
nó, nhưng nó không thể trả lại bất kỳ giá trị thông qua RETURN.
Thủ tục không thể được gọi trực tiếp từ câu lệnh SELECT, chúng có
thể được gọi là từ khối khác hoặc thông qua từ khóa EXEC.
Trang 10END [procedure_name];
Trang 11Mỗi tham số truyền vào được xác định bởi 3 loại:
Trang 131.2 Ví dụ
Một bảng user gồm ID và NAME:
create table user(id number(10) primary key,name varchar2(100));Viết một thủ tục có nhiệm vụ thêm mới một record vào bảng user
Trang 14create or replace procedure INSERTUSER (id IN NUMBER,
Trang 16create or replace procedure welcome_msg (p_name IN VARCHAR2)is
Output:
Welcome Felis
Trang 17create or replace procedure hoanvi(a in out number, b in out number)as
Trang 18dbms_output.put_line(v_a||’ ‘||v_b);end;
Output:
9 100
100 9
Trang 191.4 Xóa Procedure
giúp giải phóng bộ nhớ cho database, giúp tiết kiệm tài nguyên
DROP PROCEDURE procedure_name;
Trang 20 Function: These subprograms return a single value; mainly used to
compute and return a 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
Trang 21Creating a Function
CREATE [OR REPLACE] FUNCTION function_name [(parameter_name [IN | OUT | IN OUT] type [, ])] RETURN return_datatype
Trang 22Creating a Function
function-name specifies the name of the function.
[OR REPLACE] option allows modifying an existing function.
The optional parameter list contains name, mode and types of the parameters IN
represents that value will be passed from outside and OUT represents that this parameter will be used to return a value outside of the procedure.
The function must contain a return statement.
RETURN clause specifies that data type you are going to return from the function
function-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.
Trang 23 How to create and call a standalone function This function returns the
total number of CUSTOMERS in the customers table:
Trang 24 Function: totalCustomers
Trang 25Calling a Function
While creating a function, you give a definition of what the function
has to do To use a function, you will have to call that function to perform the defined task When a program calls a function, program control is transferred to the called function
A called function performs defined task and when its return
statement is executed or when it last end statement is reached, it
returns program control back to the main program
To call a function you simply need to pass the required parameters
along with function name and if function returns a value then you can store returned value
Trang 26Calling a Function
Following program calls the function totalCustomers from an anonymous block:
Trang 27Calling a Function
Following program calls the function totalCustomers from an anonymous block:
Trang 28PL/SQL Recursive Functions
Program or subprogram may call another subprogram When a
subprogram calls itself, it is referred to as a recursive call and the
process is known as recursion.
Trang 29PL/SQL Recursive Functions
To illustrate the concept, let us calculate the factorial of a number
Factorial of a number n is defined as:
Trang 30PL/SQL Recursive Functions
The following program calculates the factorial of a given number by calling itself
recursively:
Trang 31PL/SQL Recursive Functions
When the above code is executed at the SQL prompt, it produces the following
result:
Trang 32Difference b/w procedure and function
Procedure can performs one or more tasks where as function performs a specific
task
Procedure may or may not return value where as function should return one
value
we can call functions in select statement where as procedure we can’t
We can call function within procedure but we can not call procedure within
function
A FUNCTION must be part of an executable statement, as it cannot be executed
independently where as procedure represents an independent executable
statement.
Trang 33Built-in Functions in PL/SQL
Trang 34Conversion Functions
Trang 35String Functions
Trang 36String Functions(tt)
Trang 37Date Functions
SYSDATE() is the most commonly used Oracle date function provided by SQL*Plus.
The Oracle date function SYSDATE() returns the current date and time in the default Oracle date format
The default format for the date returned is MM-DD-YY.It's very common to use the Oracle date
function SYSDATE() in conjunction with to_char()
For example, SELECT TO_CHAR(SYSDATE, 'MM-DD-YYYY HH24:MI:SS') NOW
FROM DUAL;
select ADD_MONTHS(sysdate,-15)from dual;
ADD_MONTHS:Adds the given months to the date
Trang 38Example
Trang 39Calculates the factorial
Trang 40Function – Calculate income tax
Trang 41Function – Calculate income tax(tt)
Insert data
Trang 42Function – Calculate income tax(tt)
Display data
Trang 43Function – Calculate income tax(tt)
Calling the function
Trang 44Function – Check Palindrome String
Creating the function
Trang 45Function – Check Palindrome String(tt)
Calling the function
Trang 46Câu hỏi và bài tập?
Trang 471 Câu lệnh nào sẽ kết thúc khi thực hiện thủ tục hàm?
A. RETURN
B. EXIT
C. HALT
D. FINISH
Trang 482 REPLACE trong or replace là gì?REPLACE là optinal.
Khi từ REPLACE không được sử dụng trong tiêu đề của thủ tục, để thay đổi mã trong thủ tục,
nó phải được loại bỏ trước và sau đó được tạo lại
Trang 493 Create stored procedures to print out the name and salary of all bus drivers.
Create or replace procedure DisplayBusDrivers2 as
Begin
for driver in (select * from BusDriver)
loop
dbms_output.put_line(driver.bdname || ' ' || driver.bdsalary); end loop;
end;
Execute DisplayBusDrivers;
Trang 504 Tạo một hàm tìm kiếm course_no trả về description trong một bảng hệ cơ sở dữ liệu course với giá trị đầu vào là i_course_no?
CREATE OR REPLACE FUNCTION
show_description (i_course_no number) RETURN varchar2
WHERE course_no = i_course_no;
RETURN v_description;
EXCEPTION
WHEN NO_DATA_FOUND THEN
RETURN('The Course is not in the database');
WHEN OTHERS THEN
RETURN('Error in running show_description');
END;