0% found this document useful (0 votes)
137 views

Modul - ProgDB - 09 - Cursor 1 PDF

This document provides a syllabus for a course on Database Programming and SQL. It covers topics such as functions, procedures, triggers, and cursors in PL/SQL. Example code is provided to demonstrate how to create functions to return values based on conditions, procedures to display messages, triggers to fire on data changes, and use cursors to fetch and process query results row by row.

Uploaded by

akun hulu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

Modul - ProgDB - 09 - Cursor 1 PDF

This document provides a syllabus for a course on Database Programming and SQL. It covers topics such as functions, procedures, triggers, and cursors in PL/SQL. Example code is provided to demonstrate how to create functions to return values based on conditions, procedures to display messages, triggers to fire on data changes, and use cursors to fetch and process query results row by row.

Uploaded by

akun hulu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

MODUL PERKULIAHAN

PEMROGRAMAN
SISTEM BASIS DATA
DAN SQL

Universitas Mercu Buana


2016

Fakultas Program Studi Tatap Muka Kode MK Disusun Oleh


Ilmu Komputer Teknik Informatika 87036 Abdul Khaliq Arrachman,S.Kom.,M.Kom
07

Abstract Kompetensi
Apex adalah salah satu software tool Mahasiswa dapat menjelaskan isi pokok
yang dikembangkan oleh Oracle inc. dari mata kuliah teori dan aplikasi dari
Dalam pembuatan web aplication Apex & SQL serta membuat Aplikasi
yang sudah include di dalam oracle dari tool Apex.
10Gexpress
.
Silabus :
1.Review Function & Prosedure
2.Trigger
3.Cursor
4.Import-Export APEX

1.1. Review Function

Membuat Function Keterangan Gaji untuk tiap departement

Gaji >= 1000 bergaji tinggi

Gaji < 1000 bergaji rendah

CREATE OR REPLACE FUNCTION KET


(PDEPT IN NUMBER)
RETURN VARCHAR IS
TOT NUMBER:=0;
V_KET VARCHAR2(100);
BEGIN
SELECT SUM(T.SALARY) INTO TOT
FROM employees T
WHERE T.DEPARTMENT_ID=PDEPT;

IF TOT >= 10000 THEN


V_KET :='DEPARTMENT BERGAJI TINGGI';

ELSIF TOT < 10000 THEN


V_KET :='DEPARTMENT BERGAJI RENDAH';
ELSE
V_KET :='--';
END IF;

RETURN V_KET;
EXCEPTION
WHEN NO_DATA_FOUND THEN
TOT:=0;

END;
Membuat Function Total Gaji Tiap Departement

CREATE OR REPLACE FUNCTION TOTAL_SUMDEPT


(PDEPT IN NUMBER)
RETURN NUMBER IS
TOT NUMBER:=0;
BEGIN
SELECT SUM(T.SALARY) INTO TOT
FROM employees T
WHERE T.DEPARTMENT_ID=PDEPT;

RETURN TOT;
EXCEPTION
WHEN NO_DATA_FOUND THEN
TOT:=9999;

END;

Test Function ke dalam SQL

select T.*,TOTAL_SUMDEPT(t.department_id) ,
KET(t.department_id) from departments t;

1.2.Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE
statement. The simplified syntax for the CREATE OR REPLACE
PROCEDURE statement is as follows:

CREATE [OR REPLACE] PROCEDURE procedure_name

[(parameter_name [IN | OUT | IN OUT] type [, ...])]

{IS | AS}

BEGIN

< procedure_body >

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
END procedure_name;

Where,

 procedure-name specifies the name of the procedure.

 [OR REPLACE] option allows modifying an existing procedure.

 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.

 procedure-body contains the executable part.

 The AS keyword is used instead of the IS keyword for creating a standalone


procedure.

Example:
The following example creates a simple procedure that displays the string
'Hello World!' on the screen when executed.

CREATE OR REPLACE PROCEDURE greetings

AS

BEGIN

dbms_output.put_line('Hello World!');

END;

When above code is executed using SQL prompt, it will produce the
following result:

Procedure created.

Executing a Standalone Procedure


A standalone procedure can be called in two ways:

 Using the EXECUTE keyword

 Calling the name of the procedure from a PL/SQL block

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
The above procedure named 'greetings' can be called with the EXECUTE
keyword as:

EXECUTE greetings;

The above call would display:

Hello World

PL/SQL procedure successfully completed.

The procedure can also be called from another PL/SQL block:

BEGIN

greetings;

END;

2. TRIGGER

A trigger is a pl/sql block structure which is fired when a


DML statements like Insert, Delete, Update is executed on a

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
database table. A trigger is triggered automatically when an
associated DML statement is executed.

Creating Triggers
The syntax for creating a trigger is:

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
Where,
 CREATE [OR REPLACE] TRIGGER trigger_name: Creates or replaces an
existing trigger with the trigger_name.
 {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would
be executed. The INSTEAD OF clause is used for creating trigger on a
view.
 {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML
operation.
 [OF col_name]: This specifies the column name that would be updated.
 [ON table_name]: This specifies the name of the table associated with the
trigger.
 [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and
old values for various DML statements, like INSERT, UPDATE, and
DELETE.
 [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger
would be executed for each row being affected. Otherwise the trigger will
execute just once when the SQL statement is executed, which is called a
table level trigger.
 WHEN (condition): This provides a condition for rows for which the trigger
would fire. This clause is valid only for row level triggers.

Create Table T_EMP :


create table T_EMP
(
employee_id NUMBER(6),
first_name VARCHAR2(20),
last_name VARCHAR2(25) not null,
salary NUMBER(8,2),
department_name VARCHAR2(30) not null,
job_title VARCHAR2(35) not null,
bonus NUMBER(8,2)
)

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
CREATE OR REPLACE TRIGGER BI_T_EMP
BEFORE
insert on T_EMP
for each row
WHEN (new.salary >10000)
begin
:new.bonus:=:new.salary * 0.73;
:new.first_name:=UPPER(:new.first_name);
end;

Testing Data insert T_EMP with Trigger

insert INTO
t_emp(employee_id,first_name,last_name,salary,departm
ent_name,job_title)
sELECT
e.employee_id,e.first_name,e.last_name,e.salary,d.dep
artment_name,
j.job_title FROM employees e
join departments d on
d.department_id=e.department_id
join jobs j on j.job_id=e.job_id;

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
3.Cursors

Oracle creates a memory area, known as context area, for processing an


SQL statement, which contains all information needed for processing the
statement, for example, number of rows processed, etc.

A cursor is a pointer to this context area. PL/SQL controls the context


area through a cursor. A cursor holds the rows (one or more) returned
by a SQL statement. The set of rows the cursor holds is referred to as
the active set.

You can name a cursor so that it could be referred to in a program to


fetch and process the rows returned by the SQL statement, one at a
time. There are two types of cursors:

 Implicit cursors

 Explicit cursors

Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL
statement is executed, when there is no explicit cursor for the statement.

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
Programmers cannot control the implicit cursors and the information in
it.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an


implicit cursor is associated with this statement. For INSERT operations,
the cursor holds the data that needs to be inserted. For UPDATE and
DELETE operations, the cursor identifies the rows that would be affected.

In PL/SQL, you can refer to the most recent implicit cursor as the SQL
cursor, which always has the attributes like %FOUND, %ISOPEN,
%NOTFOUND, and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed for
use with the FORALL statement. The following table provides the
description of the most used attributes:

Attribute Description

%FOUND Returns TRUE if an INSERT, UPDATE, or DELETE statement


affected one or more rows or a SELECT INTO statement
returned one or more rows. Otherwise, it returns FALSE.

%NOTFOUND The logical opposite of %FOUND. It returns TRUE if an


INSERT, UPDATE, or DELETE statement affected no rows, or
a SELECT INTO statement returned no rows. Otherwise, it
returns FALSE.

%ISOPEN Always returns FALSE for implicit cursors, because Oracle


closes the SQL cursor automatically after executing its
associated SQL statement.

%ROWCOUNT Returns the number of rows affected by an INSERT, UPDATE,


or DELETE statement, or returned by a SELECT INTO
statement.

Any SQL cursor attribute will be accessed as sql%attribute_name as


shown below in the example.

Example:
We will be using the T_EMP table we had created and used in the
previous chapters.

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
The following program would update the table and increase salary of
each customer by 500 and use the SQL%ROWCOUNT attribute to
determine the number of rows affected:

DECLARE

total_rows number(2);

BEGIN

UPDATE t_emp

SET salary = salary + 500

WHERE salary <1000;

IF sql%notfound THEN

dbms_output.put_line('no customers selected');

ELSIF sql%found THEN

total_rows := sql%rowcount;

dbms_output.put_line( total_rows || ' customers selected ');

END IF;

END;

Explicit Cursors

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
Explicit cursors are programmer defined cursors for gaining more control
over the context area. An explicit cursor should be defined in the
declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row.

The syntax for creating an explicit cursor is :

CURSOR cursor_name IS select_statement;

Working with an explicit cursor involves four steps:

 Declaring the cursor for initializing in the memory

 Opening the cursor for allocating memory

 Fetching the cursor for retrieving data

 Closing the cursor to release allocated memory

Declaring the Cursor


Declaring the cursor defines the cursor with a name and the associated
SELECT statement. For example:

CURSOR c_employees is
SELECT
e.employee_id,e.first_name,e.last_name,e.salary,d
.department_name,
j.job_title FROM employees e
join departments d on
d.department_id=e.department_id
join jobs j on j.job_id=e.job_id;

CURSOR c_emp is
SELECT * FROM t_emp

Opening the Cursor

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
Opening the cursor allocates memory for the cursor and makes it ready
for fetching the rows returned by the SQL statement into it. For example,
we will open above-defined cursor as follows:

OPEN c_employees;

Fetching the Cursor


Fetching the cursor involves accessing one row at a time. For example
we will fetch rows from the above-opened cursor as follows:

FETCH c_employees into c_employee_id,


c_first_name,
c_last_name,c_salary,c_department_name,c_job_ti
tle;

Closing the Cursor


Closing the cursor means releasing the allocated memory. For example,
we will close above-opened cursor as follows:

CLOSE c_employee;

Example:
Following is a complete example to illustrate the concepts of explicit
cursors:
CREATE OR REPLACE PROCEDURE TEST
IS

c_employee_id employees.employee_id%type;
c_first_name employees.first_name%type;
c_last_name employees.last_name%type;
c_salary employees.salary%type;
c_department_name departments.department_name%type;
c_job_title jobs.job_title%type;

CURSOR c_employees is
SELECT
e.employee_id,e.first_name,e.last_name,e.salary,d.department_name,
j.job_title FROM employees e
join departments d on d.department_id=e.department_id
join jobs j on j.job_id=e.job_id;
BEGIN
OPEN c_employees;
LOOP

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
FETCH c_employees into c_employee_id, c_first_name,
c_last_name,c_salary,c_department_name,c_job_title;
EXIT WHEN c_employees%notfound;
dbms_output.put_line(c_employee_id || ' ' || c_first_name
|| ' ' || c_last_name|| ' ' ||c_department_name|| ' '
||c_job_title);
BEGIN
INSERT INTO
T_EMP(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY,DEPARTMENT_NAME,JOB_TI
TLE)
VALUES (c_employee_id, c_first_name,
c_last_name,c_salary,c_department_name,c_job_title);
EXCEPTION
WHEN OTHERS THEN
dbms_output.put_line(SQLERRM);
ROLLBACK;
END;

END LOOP;
COMMIT;
CLOSE c_employees;
END TEST;

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
4. EXPORT & IMPORT

4.1.WorkSpace user schema

4.2. Application

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
Export Schema
Pada windows Start- Run-Comand

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
Import Schema

DAFTAR PUSTAKA
2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id
1.abdkhaliq.com
2. www.tutorialspoint.com
3.www.plsqltutorial.com/

2016 Programan Sistem Database dan SQL Pusat Bahan Ajar dan eLearning
7 Abdul Khaliq Arrachman,S.Kom,M.Kom. http://www.mercubuana.ac.id

You might also like