UNIT-3-Ads
UNIT-3-Ads
o Header: The header contains the name of the procedure and the parameters
or variables passed to the procedure.
o Body: The body contains a declaration section, execution section and exception
section similar to a general PL/SQL block.
Table creation:
Procedure Code:
Output:
Procedure created.
PL/SQL program to call procedure
Let's see the code to call above created procedure.
1. BEGIN
2. insertuser(101,'Rahul');
3. dbms_output.put_line('record inserted successfully');
4. END;
5. /
Now, see the "USER" table, you will see one record is inserted.
ID Name
101 Rahul
PL/SQL Function
The PL/SQL Function is very similar to PL/SQL Procedure. The main difference between
procedure and a function is, a function must always return a value, and on the other
hand a procedure may or may not return a value. Except this, all the other things of
PL/SQL procedure are true for PL/SQL function too.
Here:
1. DECLARE
2. n3 number(2);
3. BEGIN
4. n3 := adder(11,22);
5. dbms_output.put_line('Addition is: ' || n3);
6. END;
7. /
Output:
Addition is: 33
Statement processed.
0.05 seconds
1. DECLARE
2. a number;
3. b number;
4. c number;
5. FUNCTION findMax(x IN number, y IN number)
6. RETURN number
7. IS
8. z number;
9. BEGIN
10. IF x > y THEN
11. z:= x;
12. ELSE
13. Z:= y;
14. END IF;
15.
16. RETURN z;
17. END;
18. BEGIN
19. a:= 23;
20. b:= 45;
21.
22. c := findMax(a, b);
23. dbms_output.put_line(' Maximum of (23,45): ' || c);
24. END;
25. /
Output:
Maximum of (23,45): 45
Statement processed.
0.02 seconds
Customers
Create Function:
After the execution of above code, you will get the following result.
Function created.
While creating a function, you have to 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. Once
the function is called, the program control is transferred to the called function.
After the successful completion of the defined task, the call function returns program
control back to the main program.
To call a function you have to pass the required parameters along with function name
and if function returns a value then you can store returned value. Following program
calls the function totalCustomers from an anonymous block:
1. DECLARE
2. c number(2);
3. BEGIN
4. c := totalCustomers();
5. dbms_output.put_line('Total no. of Customers: ' || c);
6. END;
7. /
After the execution of above code in SQL prompt, you will get the following result.
1. DECLARE
2. num number;
3. factorial number;
4.
5. FUNCTION fact(x number)
6. RETURN number
7. IS
8. f number;
9. BEGIN
10. IF x=0 THEN
11. f := 1;
12. ELSE
13. f := x * fact(x-1);
14. END IF;
15. RETURN f;
16. END;
17.
18. BEGIN
19. num:= 6;
20. factorial := fact(num);
21. dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
22. END;
23. /
After the execution of above code at SQL prompt, it produces the following result.
Factorial 6 is 720
PL/SQL procedure successfully completed.
PL/SQL Packages
PL/SQL Packages is schema object and collection of related data type (variables,
constants), cursors, procedures, functions are defining within a single context.
Package are divide into two part,
1. Package Specification
2. Package Body
Package specification block you can define variables, constants, exceptions and
package body you can create procedure, function, subprogram.
1. You can create package to store all related functions and procedures are grouped
together into single unit called packages.
2. Package are reliable to granting a privileges.
3. All function and procedure within a package can share variable among them.
4. Package are support overloading to overload functions and procedures.
5. Package are improve the performance to loading the multiple object into
memory at once, therefore, subsequent calls to related program doesn't required
to calling physically I/O.
6. Package are reduce the traffic because all block execute all at once.
Example:
CREATE or REPLACE PACKAGE BODY pkg1
IS
PROCEDURE pro1(no in number,info our varchar2)
IS
BEGIN
SELECT * INTO temp FROM emp1 WHERE eno = no;
END;
Syntax
ALTER PACKAGE package_name COMPILE BODY;
Syntax
DROP PACKAGE package_name;
Example
SQL>DROP PACKAGE pkg1;
Package dropped.
Trigger in SQL
In SQL, this concept is the same as the trigger in real life. For example, when we pull
the gun trigger, the bullet is fired.
To understand the concept of trigger in SQL, let's take the below hypothetical
situation:
Thus, now Rishabh has to create the trigger in the table, which will automatically send
a 'Congrats' message to the new employees once their record is inserted into the
database.
The trigger is always executed with the specific table in the database. If we remove the
table, all the triggers associated with that table are also deleted automatically.
In Structured Query Language, triggers are called only either before or after the
below events:
1. INSERT Event: This event is called when the new row is entered in the table.
2. UPDATE Event: This event is called when the existing record is changed or
modified in the table.
3. DELETE Event: This event is called when the existing record is removed from
the table.
In the trigger syntax, firstly, we have to define the name of the trigger after the CREATE
TRIGGER keyword. After that, we have to define the BEFORE or AFTER keyword with
anyone event.
Then, we define the name of that table on which trigger is to occur.
After the table name, we have to define the row-level or statement-level trigger.
And, at last, we have to write the SQL statements which perform actions on the
occurring of event.
The following query creates the Student_Trigger table in the SQL database:
1. DESC Student_Trigger;
Output:
The following query fires a trigger before the insertion of the student record in the
table:
To check the output of the above INSERT statement, you have to type the following
SELECT statement:
201 Sorya 88 75 69
Advantages of Triggers
These are the following advantages of Triggers:
Creating a trigger:
Syntax for creating trigger:
Here,
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:
PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.
o System-defined Exceptions
o User-defined Exceptions
1. DECLARE
2. <declarations section>
3. BEGIN
4. <executable command(s)>
5. EXCEPTION
6. <exception handling goes here >
7. WHEN exception1 THEN
8. exception1-handling-statements
9. WHEN exception2 THEN
10. exception2-handling-statements
11. WHEN exception3 THEN
12. exception3-handling-statements
13. ........
14. WHEN others THEN
15. exception3-handling-statements
16. END;
1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /
After the execution of above code at SQL Prompt, it produces the following result:
No such customer!
PL/SQL procedure successfully completed.
The above program should show the name and address of a customer as result whose
ID is given. But there is no customer with ID value 8 in our database, so the program
raises the run-time exception NO_DATA_FOUND, which is captured in EXCEPTION
block.
Note: You get the result "No such customer" because the customer_id used in the
above example is 8 and there is no cutomer having id value 8 in that table.
If you use the id defined in the above table (i.e. 1 to 6), you will get a certain result. For
a demo example: here, we are using the id 5.
1. DECLARE
2. c_id customers.id%type := 5;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /
After the execution of above code at SQL prompt, you will get the following result:
Name: alex
Address: paris
PL/SQL procedure successfully completed.
Raising Exceptions
In the case of any internal database error, exceptions are raised by the database server
automatically. But it can also be raised explicitly by programmer by using command
RAISE.
1. DECLARE
2. exception_name EXCEPTION;
3. BEGIN
4. IF condition THEN
5. RAISE exception_name;
6. END IF;
7. EXCEPTION
8. WHEN exception_name THEN
9. statement;
10. END;
1. DECLARE
2. my-exception EXCEPTION;
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.
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.
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.
ROWTYPE_MISMATCH 06504 -6504 It is raised when a cursor fetches value in a variable having
incompatible data type.
SELF_IS_NULL 30625 -30625 It is raised when a member method is invoked, but the
instance of the object type was not initialized.
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.