unit 4 sql
unit 4 sql
• The main difference between a function and a procedure is that a function always returns a
value to the calling block.
The use of OUT and IN OUT parameter types in functions is rare—and considered to
be a bad practice.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The
simplified syntax for the CREATE OR REPLACE PROCEDURE statement is as
follows −
Where,
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN
represents the value that will be passed from outside and OUT represents the
parameter that will be used to return a value outside of the function.
The function must contain a return statement.
The RETURN clause specifies the 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.
Example
The following example illustrates how to create and call a standalone function. This
function returns the total number of CUSTOMERS in the customers table.
RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following
result −
Function created.
Calling 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, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed
or when the last end statement is reached, it returns the program control back to the
main program.
To call a function, you simply need to pass the required parameters along with the
function name and if the function returns a value, then you can store the returned
value. Following program calls the function totalCustomers from an anonymous
block −
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result
−
Total no. of Customers: 6
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple
PL/SQL Function that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result
−
Maximum of (23,45): 45
TRIGGER
Triggers are stored programs, which are automatically executed or fired when some events occur. Triggers
are, in fact, written to be executed in response to any of the following events :
Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Creating Triggers
[OF col_name]
ON table_name
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
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 will 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 will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
[REFERENCING OLD AS NEW AS n] − This allows you to refer new and old values for various
DML statements, such as UPDATE
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will 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.
Example:
To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters −
The following program creates 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 −
DECLARE
sal_diff number;
BEGIN
END;
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
OLD and NEW references are not available for table-level triggers, rather you can use them for
record-level triggers.
If you want to query the table in the same trigger, then you should use the AFTER keyword, because
triggers can query the table or change it again only after the initial changes are applied and the table
is back in a consistent state.
The above trigger has been written in such a way that it will fire before any DELETE or INSERT or
UPDATE operation on the table, but you can write your trigger on a single or multiple operations,
for example BEFORE DELETE, which will fire whenever a record will be deleted using the
DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement, which
will create a new record in the table −
When a record is created in the CUSTOMERS table, the above create trigger, display_salary_changes will
be fired and it will display the following result −
Old salary:
Salary difference:
Because this is a new record, old salary is not available and the above result comes as null. Let us now
perform one more DML operation on the CUSTOMERS table. The UPDATE statement will update an
existing record in the table −
UPDATE customers
WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create trigger, display_salary_changes will
be fired and it will display the following result −
The above diagram clearly indicated that Triggers can be classified into three categories:
1. Level Triggers
2. Event Triggers
3. Timing Triggers
Level Triggers
It fires for every record that got affected with the execution of DML statements like INSERT,
UPDATE, DELETE etc.
Event Triggers
It fires with the execution of every DDL statement (CREATE, ALTER, DROP,
TRUNCATE).
It fires with the execution of every DML statement (INSERT, UPDATE, DELETE).
It fires with the execution of every database operation which can be LOGON, LOGOFF,
SHUTDOWN, SERVERERROR etc.
Timing Triggers
Triggering statement may or may not executed depending upon the before condition block.
AFTER TRIGGER
INSERT/UPDATE/DELETE Trigger
This statement specifies that Oracle will fire this trigger BEFORE the INSERT/UPDATE or DELETE
operation is executed.
Syntax
3. ON table_name
5. DECLARE
6. -- variable declarations
7. BEGIN
8. -- trigger code
9. EXCEPTION
12. END;
Where,
OR REPLACE: It is an optional parameter. It is used to re-create the trigger if it already exists. It facilitates
you to change the trigger definition without using a DROP TRIGGER statement.
trigger_name: It specifies the name of the trigger that you want to create.
BEFORE INSERT or UPDATE or DELETE: It specifies that the trigger will be fired before the INSERT
or UPDATE or DELETE operation is executed.
table_name: It specifies the name of the table on which trigger operation is being performed.
Limitations
2. ( "SUPPLIER_ID" NUMBER,
3. "SUPPLIER_NAME" VARCHAR2(4000),
4. "SUPPLIER_ADDRESS" VARCHAR2(4000)
5. )
6. /
You can use the following CREATE TRIGGER query to create a BEFORE INSERT or UPDATE or
DELETE Trigger:
2. BEFORE
5. begin
7. end;
8. /
10. /
Here the trigger name is "SUPPLIERS_T1" and it is fired BEFORE the insert or update or delete operation
is executed on the table "suppliers".
Syntax
1. CREATE [ OR REPLACE ] TRIGGER trigger_name
3. ON table_name
5. DECLARE
6. -- variable declarations
7. BEGIN
8. -- trigger code
9. EXCEPTION
12. END;
Where,
OR REPLACE: It is an optional parameter. It is used to re-create the trigger if it already exists. It facilitates
you to change the trigger definition without using a DROP TRIGGER statement.
trigger_name: It specifies the name of the trigger that you want to create.
AFTER INSERT or UPDATE or DELETE: It specifies that the trigger will be fired after the INSERT or
UPDATE or DELETE operation is executed.
table_name: It specifies the name of the table on which trigger operation is being performed.
Limitations
2. ( "SUPPLIER_ID" NUMBER,
3. "SUPPLIER_NAME" VARCHAR2(4000),
4. "SUPPLIER_ADDRESS" VARCHAR2(4000)
5. )
6. /
You can use the following CREATE TRIGGER query to create a AFTER INSERT or UPDATE or
DELETE Trigger:
5. begin
7. end;
8. /
10. /
Here the trigger name is "SUPPLIERS_T2" and it is fired AFTER the insert or update or delete operation is
executed on the table "suppliers".
Syntax
Parameters
trigger_name: It specifies the name of the trigger that you want to disable.
This example will disable the trigger called "SUPPLIERS_T2" from the table "SUPPLIERS".
If there is more than one trigger in a table and you want to disable all the triggers from the database then you
can do it by ALTER TABLE statement.
Syntax
Example
1. ALTER TABLE SUPPLIERS DISABLE ALL TRIGGERS;
This example will disable all triggers from the table "suppliers".
Syntax
Parameters
trigger_name: It specifies the name of the trigger that you want to enable.
This example will enable the trigger named "SUPPLIERS_T1" in the "SUPPLIERS" table.
Syntax
Example
This example will enable all the triggers on the table name "SUPPLIERS".