Unit-4 Advanced SQL

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

Unit-4(Advanced PL/SQL

Advanced PL/SQL Cursors – Implicit cursor – Explicit cursor – Triggers – Advantages - creating trigger – raising trigger -
Advantages of Exceptions – predefined Exceptions – user defined Exceptions .
A cursor is a pointer to this the work area or context area, used by the oracle engine for executing SQL statements. . 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.
There are two types of cursors −

 Implicit cursors
 Explicit cursors

1.Implicit Cursor(user defined cu


 The cursor which is automatically created, maintained and closed by the Oracle engine while execution of any

DML(Data Manipulation Language) queries like INSERT, UPDATE or DELETE are called Implicit Cursor.

 Implicit Cursors are controlled by Oracle Engine hence programmers cannot access its information.

 When a DML statement is executed an implicit cursor is created and attached to it.

To work with the cursor whether Implicit or Explicit cursor, there are following attributes which are used:

ATTRIBUTE DESCRIPTION
NAME
%ISOPEN If cursor is open it returns a Boolean value TRUE otherwise it
returns Boolean value FALSE
%FOUND If records fetched by cursor was successful it returns Boolean
value TRUE otherwise it returns Boolean value FALSE
%NOTFOUND If records fetched by cursor was unsuccessful it returns
Boolean value TRUE otherwise it returns Boolean
value FALSE
%ROWCOUNT It returns the number of rows affected by PL/SQL statement

SQL> select*from emp;

ID NAME AGE ADDRESS SAL


---------- ---------- ---------- --------------- ----------------
1 james 20 UK 22000
2 stephen 26 dubai 17000
3 david 27 bangkok 22000
4 alina 29 uk 67000

The following program will update the table and increase the salary of each customer by 500 and use the SQL
%ROWCOUNT attribute to determine the number of rows affected 

SQL> DECLARE
2 total_rows number(2);
3 BEGIN
4 UPDATE emp
5 SET sal = sal + 1000;

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


6 IF sql%notfound THEN
7 dbms_output.put_line('no customers selected');
8 ELSIF sql%found THEN
9 total_rows := sql%rowcount;
10 dbms_output.put_line( total_rows || ' customers selected ');
11 END IF;
12 END;
13 /
4 customers selected

PL/SQL procedure successfully completed.

SQL> select*from emp;

ID NAME AGE ADDRESS SAL


---------- ---------- ---------- --------------- -----------------
1 james 20 UK 23000
2 stephen 26 dubai 18000
3 david 27 bangkok 23000
4 alina 29 uk 68000

2.Explicit Cursor(Predefined cursor)


The cursor which has to be created, maintained and closed by a program through PL/SQL code for the execution of
any SELECT query that returns more than one row is called Explicit Cursor.It is a user-defined cursor declared in
the Declare section of PL/SQL block and is used in its Executable section.The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;

Working with an explicit cursor includes the following steps −

1.Declaring the Cursor(Declaring the cursor for initializing the memory)


Syntax:CURSOR <cursor_name> IS <SELECT query>;

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

CURSOR c_customers IS
SELECT id, name, address FROM customers;
2.Opening the cursor:Opening the cursor for allocating the memory(it ready for fetching the rows returned by the SQL
statement into I)t
OPEN <cursor_name>; OPEN c_customers;
3.Fetching the Cursor(for retrieving the data) Fetching the cursor involves accessing one row at a time.
fetch <cursor_name> into <list_of_variables>;
FETCH c_customers INTO c_id, c_name, c_addr;
4.losing the cursor (to release the allocated memory)
CLOSE cursorname;

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


SQL> select*from customers1;
C_ID C_NAME C_ADDRESS
---------- ---------- ----------
1 ravi nandyala
2 arun kurnool
3 ramesh hyderbad
4 rajesh hyderbad
2.Explicit cursor program
SQL> DECLARE
2 c_id customers1.c_id%type;
3 c_name customers1.c_name%type;
4 c_address customers1.c_address%type;
5 CURSOR c_customers1 is
6 SELECT c_id, c_name, c_address FROM customers1;
7 BEGIN
8 OPEN c_customers1;
9 LOOP
10 FETCH c_customers1 into c_id, c_name, c_address;
11 EXIT WHEN c_customers1%notfound;
12 dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_address);
13 END LOOP;
14 CLOSE c_customers1;
15 END;
16 /
1 ravi nandyala
2 arun kurnool
3 ramesh hyderbad
4 rajesh hyderbad
PL/SQL procedure successfully completed.
A trigger is a stored procedure in a database that automatically invokes whenever a special event in the database occurs.

TRIGGERS are stored programs that are fired(called by Oracle engine automatically when DML Statements like insert,
update, delete are executed on the table or some events occur. You can choose the event upon which the trigger
needs to be fired and the timing of the execution. The purpose of trigger is to maintain the integrity of information on
the database. a trigger can be invoked when a row is ins

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


Triggers are written to be executed in response to any of the following events.

A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).

A database definition (DDL) statement (CREATE, ALTER, or DROP).

A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or SHUTDOWN).

Advantages of Triggers
Following are the benefits of triggers.

 Triggers-generates some derived column values automatically


 Enforcing referential integrity
 Event logging and storing information on table access
 Auditing
 Synchronous replication of tables
 Imposing security authorizations
 Preventing invalid transactions

Types of Triggers in Oracle

Triggers can be classified based on the following parameters.

Classification based on the timing

BEFORE Trigger: It fires before the specified event has occurred.

AFTER Trigger: It fires after the specified event has occurred.

Classification based on the level

STATEMENT level Trigger: It fires one time for the specified event statement.

ROW level Trigger: It fires for each record that got affected in the specified event. (only for DML)

Classification based on the Event

DML Trigger: It fires when the DML event is specified (INSERT/UPDATE/DELETE)

DDL Trigger: It fires when the DDL event is specified (CREATE/ALTER)

Create DATABASE Trigger: It fires when the database event is specified (LOGON/LOGOFF/STARTUP/SHUTDOWN)

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


where

CREATE OR REPLACE TRIGGER is a keyword used to create a trigger and <trigger_name> is user-defined where a trigger
can be given a name.

BEFORE/AFTER/INSTEAD OF specify the timing of the trigger's occurance. INSTEAD OF is used when a view is created.

INSERT/UPDATE/DELETE specify the DML statement.

<table_name> specify the name of the table on which DML statement is to be applied.

REFERENCING is a keyword used to provide reference to old and new values for DML statements.

FOR EACH ROW is the clause used to specify row level tigger.

WHEN is a clause used to specify condition to be applied and is only applicable for row-level trigger.

DECLARE, BEGIN, EXCEPTION, END are the different sections of PL/SQL code block containing variable declaration,
executable statements, error handling statements and marking end of PL/SQL block respectively where DECLARE and
EXCEPTION part are optional.

PL/SQL Trigger Example

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

4 Chandan 25 Noida 26000

5 Alex 21 Paris 28000

6 Sunita 20 Delhi 30000

Create trigger:

Let's take a program to create a row level trigger for the CUSTOMERS table that would fire for INSERT or UPDATE or DELETE operations performed on
the CUSTOMERS table. This trigger will display the salary difference between the old values and new values:

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


1. CREATE OR REPLACE TRIGGER display_salary_changes  
2. BEFORE DELETE OR INSERT OR UPDATE ON customers  
3. FOR EACH ROW  
4. WHEN (NEW.ID > 0)  
5. DECLARE  
6.    sal_diff number;  
7. BEGIN  
8.    sal_diff := :NEW.salary  - :OLD.salary;  
9.    dbms_output.put_line('Old salary: ' || :OLD.salary);  
10.    dbms_output.put_line('New salary: ' || :NEW.salary);  
11.    dbms_output.put_line('Salary difference: ' || sal_diff);  
12. END;  
13. /  

After the execution of the above code at SQL Prompt, it produces the following result.

Trigger created.

Check the salary difference by procedure:

Use the following code to get the old salary, new salary and salary difference after the trigger created.

Old salary: 25000


New salary: 30000
1. DECLARE    Salary difference: 5000
Old salary: 27000
2.    total_rows number(2);   New salary: 32000
3. BEGIN   Salary difference: 5000
Old salary: 29000
4.    UPDATE  customers   New salary: 34000
Salary difference: 5000
5.    SET salary = salary + 5000;   Old salary: 31000
6.    IF sql%notfound THEN   New salary: 36000
Salary difference: 5000
7.       dbms_output.put_line('no customers updated');   Old salary: 33000
8.    ELSIF sql%found THEN   New salary: 38000
Salary difference: 5000
9.       total_rows := sql%rowcount;   Old salary: 35000
New salary: 40000
10.       dbms_output.put_line( total_rows || ' customers updated ');   Salary difference: 5000
11.    END IF;    6 customers updated
12. END;  
13. /  
when specific table columns are updated in simple words a trigger is a collection of SQL statements with particular
names that are stored in system memory. It belongs to a specific class of stored procedures that are automatically
invoked in response to database server events. gsg
A trigger is a stored procedure in a database that automatically invokes whenever a special event in the database
occurs. For example, a trigger can be invoked when a row is inserted into a specified table or when specific table
columns are updated in simple words a trigger is a collection of SQL statements with particular names that are An a

A error occurs during the program execution is called Exception in PL/SQL.

Exception-Handling

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


 A error occurs during the program execution is called Exception in PL/SQL.
 For example, if PL/SQL engine receives an instruction to divide any number by ‘0’, then the PL/SQL engine will throw
it as an exception. The exception is only raised at the run-time by the PL/SQL engine.

 Exceptions will stop the program from executing further, so to avoid such condition, they need to be captured and
handled separately. This process is called as Exception-Handling, in which the programmer handles the exception
that can occur at the run time.

Syntax:

fiBEGIN
<execution block>
.
.
EXCEPTION
WHEN <exceptionl_name>
THEN
<Exception handling code for the “exception 1 _name’' >
WHEN OTHERS
THEN
<Default exception handling code for all exceptions >
END;
c clas

Advantages of PL/SQL Exceptions

 It is possible to handle potential errors from many statements by using a single exception handler.
 If user needs to check for error at every point, it is solved by adding an exception handler to PL/SQL block in the
program.
 To check error at a specific spot is possible by enclosing a single statement or a group of statements inside its own
exception handler.
 Isolating error handling method makes the rest of the program easier to read and understand

Type sof exceptions:

There are two type of exceptions:

o User-defined Exceptions
o System-defined Exceptions

PL/SQL User-defined Exceptions

PL/SQL facilitates their users to define their own exceptions according to the need of the program. A user-defined
exception can be raised explicitly, using either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


Syntax for user define exceptions

DECLARE  
my-exception EXCEPTION;   
SQL>edit user_expDECLARE
myex EXCEPTION;
i NUMBER;BEGIN
FOR i IN (SELECT * FROM enum) LOOP
IF i.eno = 3 THEN
RAISE myex;
END IF;
END LOOP;
EXCEPTION
WHEN myex THEN
dbms_output.put.line('Employee number already exist in enum table.');END;/
Result

SQL>@user_exp
Employee number already exist in enum table.

PL/SQL procedure successfully operation.

2. PL/SQL Pre-defined Exceptions: There are many pre-defined exception in PL/SQL which are executed when any
database rule is violated by the programs.For example: NO_DATA_FOUND is a pre-defined exception which is raised
when a SELECT INTO statement returns no rows.

Exception Oracle SQL Description


Error Code

ACCESS_INTO_NULL 06530 -6530 It is raised when a NULL object is automatically


assigned a value.

CASE_NOT_FOUND 06592 -6592 It is raised when none of the choices in the


"WHEN" clauses of a CASE statement is
selected, and there is no else clause.

DUP_VAL_ON_INDEX 00001 -1 It is raised when duplicate values are attempted


to be stored in a column with unique index.

INVALID_CURSOR 01001 -1001 It is raised when attempts are made to make a


cursor operation that is not allowed, such as
closing an unopened cursor.

INVALID_NUMBER 01722 -1722 It is raised when the conversion of a character


string into a number fails because the string
does not represent a valid number.

LOGIN_DENIED 01017 -1017 It is raised when s program attempts to log on


to the database with an invalid username or
password.

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR


NO_DATA_FOUND 01403 +100 It is raised when a select into statement returns
no rows.

NOT_LOGGED_ON 01012 -1012 It is raised when a database call is issued


without being connected to the database.

PROGRAM_ERROR 06501 -6501 It is raised when PL/SQL has an internal


problem.

ROWTYPE_MISMATCH 06504 -6504 It is raised when a cursor fetches value in a


variable having incompatible data type.

STORAGE_ERROR 06500 -6500 It is raised when PL/SQL ran out of memory or


memory was corrupted.

TOO_MANY_ROWS 01422 -1422 It is raised when a SELECT INTO statement


returns more than one row.

VALUE_ERROR 06502 -6502 It is raised when an arithmetic, conversion,


truncation, or size-constraint error occurs.

ZERO_DIVIDE 01476 1476 It is raised when an attempt is made to divide a


number by zero.

Ex:NO_DATA_FOUND: It is raised when a select into statement returns no rows.



 DECLARE
DECLARE
 2 2temp temp varchar(20);
varchar(20);
3
 4 BEGIN
3
 5 4SELECT
BEGINg_id into temp from geeks where
g_name='GeeksforGeeks';
 6 5 SELECT g_id into temp from geeks where g_name='GeeksforGeeks';
7 exception
 8 6WHEN no_data_found THEN
 9 7 exception
dbms_output.put_line('ERROR');
10 dbms_output.put_line('there is no name as');
 11 8 dbms_output.put_line('GeeksforGeeks
WHEN no_data_found THEN in geeks table');
12 end;
 9 dbms_output.put_line('ERROR');
13 /
ERROR10 dbms_output.put_line('there is no name as');
there is no name as
GeeksforGeeks
11 dbms_output.put_line('GeeksforGeeks
in geeks table in geeks table');
 12 end;
 13 /
 ERROR
 there is no name as
 GeeksforGeeks in geeks table
 s of stored procedures that are automatically invoked in response to database server events.

PREPARED BY B.KIRAN BABU.,M.TECH CSE SVREC ASSISTANT PROFESSOR

You might also like