Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Arijit Dbms

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 59

15IT302J - DATABASE MANAGEMENT SYSTEM LAB

SEMESTER V

YEAR : 2019 - 2020

NAME : ARIJIT NAYAK


REGISTER NO : RA1711020010098

DEPARTMENT OF SOFTWARE ENGINEERING


SRM INSTITUTE OF SCIENCE AND TECHNOLOGY
(Under Section 3 of UGC Act, 1956)
S.R.M Nagar, Kattankulathur - 603203
Kancheepuram District
INDEX
Exp. No. Date Date Marks Sign
of Title of
Experiment Submission
1 05-07-2019 About the Project 12-07-2019
2 12-07-2019 Entity Relationship Diagram 19-07-2019
3 19-07-2019 Relational Model 26-07-2019
4 26-07-2019 SQL Data Definition Language Commands 02-08-2019
5 02-08-2019 SQL Data Manipulation Language Commands 09-08-2019
6 09-08-2019 Inbuilt functions in SQL 20-08-2019
7 20-08-2019 Sub Queries 27-08-2019
8 20-08-2019 Nested Queries 27-08-2019
9 27-08-2019 Join Queries 04-09-2019
10 04-09-2019 Set Operations 12-09-2019
11 04-09-2019 Views 12-09-2019
12 12-09-2019 PL/SQL Conditional and Iterative Statements 19-09-2019
13 19-09-2019 PL/SQL Procedures 26-09-2019
14 19-09-2019 PL/SQL Functions 26-09-2019
15 26-09-2019 PL/SQL Cursors 04-10-2019
16 04-10-2019 PL/SQL Exception Handling 14-10-2019
17 04-10-2019 PL/SQL Trigger 14-10-2019
18 14-10-2019 Project Code 21-10-2019
19 14-10-2019 Screenshots 21-10-2019

PROJECT REPORT
SOFTWARE DEVELOPED NAME : BOOK-n-UP

OBJECTIVE:- This is a online bookshop where you can use it as a option to buy some books. If you
want you can fix as your University Official Bookshop. As of now it’s been designed on that context
only. This online book store is adaptable to various different use of general online book shopping with
various stationery as add on feature. Also customization to university or corporate book can be done if a
client register.

MODULES:-
1. Login for Admin and Users
2. Book Details
3. Purchase and Sales

ENTITIES:-
1. BookDetails
2. Login
3. Admin
4. Cart
5. Department Details
6. Stream_Table

RELATIONSHIP:-
1. First of all user books will be added by Admin only and their all kind of details
2. A user will signup with their reg id to website and log in with that credentials.
3. A user will first need to choose stream.
4. Each stream having each table and that will be connected to some department content.
5. As per the department we will add some values to it and, after that we will able to see our data.

ENTITY-RELATION DIAGRAM:-
ER Diagram:-
Relation Model
Table:-
GRAPHICAL USER INTERFACE (GUI):-
For this project the GUI is made using html and css. Frontend includes the use of materialize
css,Boostrap 4 and in backend php is used with mysql as a database.
Database name is ‘bookshop’ and It has 5 tables:-
1. bookdetails
2. cart_history
3. department
4. engineering
5. link
6. login
7. medical
8. stream
It is a multi page web application which has various buttons. Each button is associated with a specified
operation in the backend which fetches the data from the database as and when required.

The operations included in the Project Kart-Out are:-


1. select
2. insert
3. set operations
4. delete
5. aggregate functions or inbuilt functions
6. update
7. group by
8. inner join
9. Sub queries
EXCERISE – 1
Data Definition Language SQL COMMANDS

Data Definition Language (DDL) statements are used to define the database structure orschema. Some
examples:

 CREATE - to create objects in the database


 ALTER - alters the structure of the database o DROP - delete objects from the database
 TRUNCATE - remove all records from a table, including all spaces allocated for the records are
removed
 COMMENT - add comments to the data dictionary
 RENAME - rename an object

The Create Table Command

The create table command defines each column of the table uniquely. Each column has minimum of three
attributes.
 Name
 Data type
 Size(column width).

Each table column definition is a single clause in the create table syntax. Each table column definition is
separated from the other by a comma. Finally, the SQL statement is terminated with a semicolon.

Syntax
CREATE TABLE table_name(column1 datatype, column2 datatype,….);

The DROP Command


Syntax:
DROP TABLE <table_name>

The TRUNCATE Command


Syntax:
TRUNCATE TABLE <table_name>
The RENAME Command
Syntax:
RENAME <OldTableName> TO <NewTableName>

The ALTER Table Command


By The use of ALTER TABLE Command we can modify our exiting table.
Adding New Columns
Syntax:
ALTER TABLE <table_name> ADD (<NewColumnName><Data_Type>(<size>),......n)

Dropping a Column from the Table


Syntax:
ALTER TABLE <table_name> DROP COLUMN <column_name>

CREATE:-
Query:- CREATE TABLE customers(Name text, Email varchar(50), Contact int(10),Location text, Password
varchar(15))”

PROJECT CODES
EXP-1: DDL Commands:
SELECT:- (need to give the query for all the tables created)
Query:- CREATE TABLE login(username varchar(100),password varchar(1000),mail_id
varchar(50),u_co varchar(50),u_img varchar(100),ref number,address varchar(1000));
Output:-

Figure 1 - Table Creation


EXCERISE – 2
DML (Data Manipulation Language)

DML statements affect records in a table. These are basic operations we perform on data such as
selecting a few records from a table, inserting new records, deleting unnecessary records, and
updating/modifying existing records.

DML statements include the following:

 SELECT –select records from a table


 INSERT –insert new records
 UPDATE –update/Modify existing records
 DELETE –delete existing records

DML command
Data Manipulation Language (DML) statements are used for managing data in database. DML
commands are not auto-committed. It means changes made by DML command are not permanent to
database, it can be rolled back.

INSERT COMMAND
Insert command is used to insert data into a table. Following is its general syntax,

Syntax
INSERT intotable-namevalues(data1,data2,..)

UPDATE COMMAND
Update command is used to update a row of a table. Following is its general syntax,

Syntax
UPDATE table-nameset column-name = valuewhere condition;

DELETE COMMAND
Delete command is used to delete data from a table. Delete command can also be used with condition to
delete a particular row. Following is its general syntax,

Syntax
DELETE fromtable-name;

SELECT COMMAND
SELECT Query
Select query is used to retrieve data from a tables. It is the most used SQL query. We can retrieve
complete tables, or partial by mentioning conditions using WHERE clause.

Syntax of SELECT Query


SELECT column-name1, column-name2, column-name3, column-name fromtable-name;

Like Clause
Like clause is used as condition in SQL query. Like clause compares data with an expression using
wildcard operators. It is used to find similar data from the table.

Order By Clause
Order by clause is used with Select statement for arranging retrieved data in sorted order. The Order
byclause by default sort data in ascending order. To sort data in descending order DESC keyword is
used withOrder by clause.

Syntax of Order By
SELECT column-list|* from table-nameorder byasc|desc;
Group By Clause
Group by clause is used to group the results of a SELECT query based on one or more columns. It is
also used with SQL functions to group the result from one or more tables.

Syntax for using Group by in a statement.


SELECT column_name, function(column_name)
FROM table_name WHERE condition GROUP BY column_name
EXP-2: DML Commands
SELECT:-
Query:-"SELECT * FROM engineering where tablename=’”.$link.”’";
Output:-

INSERT:-
Query:- "INSERT Into login (‘username’,’password’,’mail_id’,’u_co’,’ref’,’u_img’) values (‘”.$m1.”’,‘”.
$pa.”’,‘”.$m4.”’,‘”.$m5.”’,‘”.$ref.”’,‘”.$cloc.”’)";
Output:-
Insert Value In DB:

UPDATE:-
Query:-"UPDATE `cart_history` SET `b_q`=’”.$total_quan.”’ “,`total_p`=’”.$total_rs.”’ WHERE
`b_id`=`”.$id_book.”` and `username`=’”.$_SESSION[‘uname’][‘username’].”’

Output:-
DELETE:-
Query:-"DELETE FROM ‘cart_history’ WHERE b_id=’”.$r.”’ and username=’”.$_SESSION[‘unmae’]
[‘username’].”’ ";
Output:-
EXCERISE – 3

Built-In functions in SQL


1. avg
Syntax: select avg (colname) from table_name;

2.max
Syntax: select max (colname) from table_name;

3.min
Syntax: select min (colname) from table_name;

4. sum
Syntax: select sum (colname) from table_name;

Count Function
In order to count the number of rows, count function is used.

1. count(*) –It counts all, inclusive of duplicates and nulls. Example: select count(*) from student;
2. count(col_name)– It avoids null value.
3. count(distinct col_name) –It avoids the repeated and null values. Example: select count(distinct
ordid) from order;
EXP-3 Inbuilt Functions CODE
SUM:-
Query:-"SELECT mode_p,SUM(amount) from payment_gateway GROUP BY mode_p";
Output:-

EXERCISE– 4
JOIN QUERIES

Cross JOIN or Cartesian Product

This type of JOIN returns the cartesian product of rows from the tables in Join. It will return a table which consists
of records which combines each row from the first table with each row of the second table.

Cross JOIN Syntax is,


SELECT column-name-list

fromtable-name1

CROSS JOIN
table-name2;

INNER Join or EQUI Join

This is a simple JOIN in which the result is based on matched data as per the equality condition specified in the
query.
Inner Join Syntax is,

SELECT column-name-list
fromtable-name1

INNER JOIN
table-name2
WHERE table-name1.column-name = table-name2.column-name;

Natural JOIN

Natural Join is a type of Inner join which is based on column having same name and same datatype present in both
the tables to be joined.

Natural Join Syntax is,


SELECT *

fromtable-name1

NATURAL JOIN
table-name2;

Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
 Left Outer Join

 Right Outer Join


 Full Outer Join

Left Outer Join

The left outer join returns a result table with the matched data of two tables then remaining rows of the left table
and null for the right table's column.
Left Outer Join syntax is,
SELECT column-name-list

fromtable-name1

LEFT OUTER JOIN


table-name2

on table-name1.column-name = table-name2.column-name;

Left outer Join Syntax for Oracle is,


select column-name-list

fromtable-name1,
table-name2
on table-name1.column-name = table-name2.column-name(+);

Right Outer Join

The right outer join returns a result table with the matched data of two tables then remaining rows of the right
table and null for the left table's columns.
Right Outer Join Syntax is,

select column-name-list
fromtable-name1

RIGHT OUTER JOIN


table-name2

on table-name1.column-name = table-name2.column-name;

Full Outer Join


The full outer join returns a result table with the matched data of two table then remaining rows of both left table
and then the right table.

Full Outer Join Syntax is,


select column-name-list

fromtable-name1

FULL OUTER JOIN


table-name2

on table-name1.column-name = table-name2.column-name;

CODE FOR -Join Queries

INNER JOIN:-
Query:-"SELECT distinct bookdetails.b_name, bookdetails.b_id FROM department INNER JOIN link ON
department.d_id=link.id INNER JOIN bookdetails ON link.b_id=bookdetails.b_id";
Output:-
EXCERISE – 5 & 6

SQL SUBQUERIES AND SET OPERATIONS

Subquery or Inner query or Nested query is a query in a query. SQL subquery is usuallyadded in the WHERE
Clause of the SQL statement. Most of the time, a subquery is used when you know how to search for a value
using a SELECT statement, but do not know the exact value in the database.

Subqueries are an alternate way of returning data from multiple tables.

Subqueries can be used with the following SQL statements along with the comparision operators like =, <, >,
>=, <= etc.

 SELECT

 INSERT
 UPDATE

 DELETE

EXAMPLE:-

SELECT No_Of_Copies

FROM BOOK_COPIES, BOOK, LIBRARY_BRANCH


WHERE BOOK_COPIES.BranchId = LIBRARY_BRANCH.BranchIdAND

BOOK_COPIES.BookId = BOOK.BookId AND


BOOK.Title = "The Lost Tribe" AND

LIBRARY_BRANCH.BranchName = "Sharpstown";
The Set operator combines the result of 2 queries into a single result.The following are the operators:
· Union

· Union all
· Intersect

· Minus
Union:
Returns all distinct rows selected by both the queries

Syntax:
Query1 Union Query2;

Union all:
Returns all rows selected by either query including the duplicates.

Syntax:
Query1 Union all Query2;

Intersect
Returns rows selected that are common to both queries.

Syntax:
Query1 Intersect Query2;

Minus
Returns all distinct rows selected by the first query and are not by the second

Syntax:
Query1 minus Query2;

CODE FOR – 5 &6


SUBQUERY:-
Query:-
$sql="SELECT *FROM bookdetails where b_idin(select b_id from link where id='".$t."')";
Output:-

UNION:-
Query:-

"SELECT a.id,a.name,a.rating,b.id from send_agent a LEFT JOIN rec_agent b ON a.id = b.id";


UNION ALL
"SELECT a.id,a.name,a.rating,b.id from send_agent a RIGHT JOIN rec_agent b ON a.id = b.id";
Output:-

EXCERISE – 7

PL/SQL
PROGRAMS

In addition to SQL
commands,PL/SQL
can also process
data using flow of
statements. The
flow of control
statements are
classified into the
following
categories.
· Conditional control -Branching

· Iterative control - looping

· Sequential control

BRANCHING in PL/SQL:

Sequence of statements can be executed on satisfying certain condition . If statements are being used and different
forms of if are:

1) Simple IF

2) If-Else

3) Nested IF

SIMPLE IF:

Syntax

IF condition THEN statement1; statement2;

END IF;

IF-THEN-ELSE STATEMENT:

Syntax:

IF condition THEN statement1;

ELSE statement2;
END IF;

ELSIF STATEMENTS:

Syntax:

IF condition1 THEN statement1;

ELSIF condition2 THEN statement2;

ELSIF condition3 THEN statement3;

ELSE statement;

END IF;

NESTED IF :

Syntax:

IF condition THEN statement1;

ELSE

IF condition THEN statement2;

ELSE statement3;

END IF;

END IF;
ELSE statement3;

END IF;

SIMPLE CASE

Syntax:

CASE SELECTOR

WHEN Expr1 THEN statement1;

WHEN Expr2 THEN statement2;

ELSE Statement n;

END CASE;

SEARCHED CASE:

CASE
WHEN searchcondition1 THEN statement1;

WHEN searchcondition2 THEN statement2;


:

:
ELSE statement n;

END CASE;
ITERATIONS IN PL/SQL

Sequence of statements can be executed any number of times using loop construct. It is broadly classified into:

· Simple Loop
· Loop
· While Loop

SIMPLE LOOP

Syntax:

LOOP statement1;

EXIT [ WHEN Condition];

END LOOP;

WHILE LOOP

Syntax

WHILE condition LOOP statement1; statement2;

END LOOP;

FOR LOOP

Syntax:

FOR counter IN [REVERSE] LowerBound..UpperBound

LOOP
statement1;
statement2;

END LOOP;

DECLARE

sales NUMBER(8,2) := 10100;

quota NUMBER(8,2) := 10000;

bonus NUMBER(6,2);

emp_id NUMBER(6) := 120;

BEGIN

IF sales > (quota + 200) THEN

bonus := (sales - quota)/4;

UPDATE employees SET salary = salary + bonus WHERE employee_id = emp_id;

END IF;

END;

DECLARE

grade CHAR(1);
EGIN
grade := 'B';

CASE grade

WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');

WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Very Good');

WHEN 'C' THEN DBMS_OUTPUT.PUT_LINE('Good');

WHEN 'D' THEN DBMS_OUTPUT.PUT_LINE('Fair');

WHEN 'F' THEN DBMS_OUTPUT.PUT_LINE('Poor');

ELSE DBMS_OUTPUT.PUT_LINE('No such grade');

END CASE;

END;

DECLARE

p NUMBER := 0;

BEGIN

FOR k IN 1..500 LOOP -- calculate pi with 500 terms

p := p + ( ( (-1) ** (k + 1) ) / ((2 * k) - 1) );
END LOOP;

p := 4 * p;

DBMS_OUTPUT.PUT_LINE( 'pi is approximately : ' || p ); -- print result

END;

DECLARE

p VARCHAR2(30);

n PLS_INTEGER := 37; -- test any integer > 2 for prime

BEGIN

FOR j in 2..ROUND(SQRT(n)) LOOP

IF n MOD j = 0 THEN -- test for prime

p := ' is not a prime number'; -- not a prime number

GOTO print_now;

END IF;

END LOOP;

p := ' is a prime number';


<<print_now>>

DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);

END;

PL/SQL VIEW
VIEWS A view is the tailored presentation of data contained in one or more table and can also be said as restricted
view to the data’s in the tables. A view is a “virtual table” or a “stored query” which takes the output of a query and
treats it as a table. The table upon which a view is created is called as base table.

Advantages of a view:
a. Additional level of table security.
b. Hides data complexity.
c. Simplifies the usage by combining multiple tables into a single table.
d. Provides data‟s in different perspective.

Types of view:
Horizontal -> enforced by where cause
Vertical -> enforced by selecting the required columns
SQL Commands for Creating and dropping view:

Syntax:
Create [or replace] view [column alias names] as [with conditions];
Drop view ;
Code-
$user_mail=$_POST['single_user_mailid'];
$sql1= "
create or replace view fetchview as select * from login where mail_id='".$user_mail."';";
$sql ="
SELECT * FROM fetchview";
$r1=mysqli_query($con,$sql1);
$r=mysqli_query($con,$sql);

OutPut :

EXCERISE – 8PROCEDURES IN PL/SQL

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 schemalevel
 Inside a package
 Inside a PL/SQLblock

At the schema level, subprogram is a standalone subprogram. It is created with the CREATE PROCEDURE
or the CREATE FUNCTION statement. It is 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 the DROP PACKAGE statement. We will discuss packages in
the chapter 'PL/SQL - Packages'.

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−Thesesubprogramsreturnasinglevalue;mainlyusedtocomputeandreturn avalue.

 Procedures − These subprograms do not return a value directly; mainly used to perform anaction.
Parts of a PL/SQL Subprogram
Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous PL/SQL blocks,
the named blocks will also have the following three parts –

S.No Parts & Description


Declarative Part
It is an optional part. However, the declarative part for asubprogram
1 does not start with the DECLARE keyword. It contains declarations
of types, cursors, constants, variables, exceptions, and nested
subprograms. These items are local to the subprogram and cease to
exist when the subprogram completesexecution.
Executable Part
2 This is a mandatory part and contains statements that perform the
designated action.
Exception-handling
3 This is again an optional part. It contains the code that handles run-
time errors.

Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDUREstatement. 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>
END procedure_name;

Where,
 procedure-namespecifies the name of theprocedure.
 [OR REPLACE] option allows the modification of an existingprocedure.
 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 theprocedure.
 procedure-bodycontains the executablepart.
 The AS keyword is used instead of the IS keyword for creating a standaloneprocedure.

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 the above code is executed using the 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 EXECUTEkeyword
 Calling the name of the procedure from a PL/SQLblock
The above procedure named 'greetings' can be called with the EXECUTE keyword as −

EXECUTE greetings;
The above call will display −

Hello World

PL/SQL procedure successfully completed.

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

BEGIN
greetings;
END;
/

The above call will display −

Hello World

PL/SQL procedure successfully completed.

Deleting a Standalone Procedure


Astandaloneprocedure isdeletedwiththeDROPPROCEDUREstatement.Syntaxfordeleting a procedure is−

DROP PROCEDURE procedure-name;

You can drop the greetings procedure by using the following statement −

DROP PROCEDURE greetings;

Parameter Modes in PL/SQL Subprograms


The following table lists out the parameter modes in PL/SQL subprograms −
S.No Parameter Mode & Description

IN
An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot be
1 assigned a value. You can pass a constant, literal, initialized variable, or
expressionasanINparameter.Youcanalsoinitialize ittoadefaultvalue;however, in that
case, it is omitted from the subprogram call. It is the default mode of parameter
passing. Parameters are passed byreference.
OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an
2 OUT parameter acts like a variable. You can change its value and reference the value
after assigning it. The actual parameter must be variable and it is passed by
value.
3 IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an
updated value to the caller. It can be assigned a value and the value can be read.
The actual parameter corresponding to an IN OUT formal parameter must be a
variable, not a constant or an expression. Formal parameter must be assigned a
value. Actual parameter is passed by value.

IN & OUT Mode Example 1


This program finds the minimum of two values. Here, the procedure takes two numbers using the IN mode and
returns their minimum using the OUT parameters.
DECLARE
a number; b number; cnumber;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS BEGIN
IF x < y THEN
z:= x; ELSE
z:= y; END IF;
END; BEGIN
a:=23;
b:=45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c); END;
/

When the above code is executed at the SQL prompt, it produces the following result −

Minimum of (23, 45) : 23

PL/SQL procedure successfully completed.

FUNCTIONS IN PL/SQL
A function is same as a procedure except that it returns a value. Therefore, all the discussions of the previous
chapter are true for functions too.

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 −

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
<function_body>
END [function_name];

Where,

 function-namespecifies the name of thefunction.

 [OR REPLACE] option allows the modification of an existingfunction.

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

 The function must contain a returnstatement.

 The RETURN clause specifies the data type you are going to return from thefunction.

 function-bodycontains the executable part.

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

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.

We will use the CUSTOMERS table, which we had created in the PL/SQL Variableschapter −

Select * from customers;


+----+----------+-----+-----------+----------+
| ID|NAME | AGE | ADDRESS | SALARY|
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25|Delhi |1500.00|
| 3 | kaushik | 23|Kota |2000.00|
| 4 | Chaitali | 25|Mumbai | 6500.00 |
| 5 | Hardik | 27|Bhopal | 8500.00 |
| 6|Komal | 22|MP | 4500.00|
+----+----------+-----+-----------+----------+

CREATE OR REPLACE FUNCTION totalCustomers RETURN


number IS

total number(2) := 0;
BEGIN

SELECT count(*) into total


FROM customers;
When the above code is executed using the SQL prompt, it will produce the following result −

Function
RETURNcreated.
total;
END;
/Calling a Function
Whilecreatingafunction,yougiveadefinitionofwhatthefunctionhastodo.Touseafunction, 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
calledfunction.

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.

Tocalla function,yousimplyneedtopasstherequiredparametersalongwiththefunctionname
andifthefunctionreturnsavalue,thenyoucanstorethereturnedvalue.Followingprogramcalls the function
totalCustomersfrom 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

PL/SQL procedure successfully completed.

EXCERISE - 9CURSORS
A cursor is a pointer to this context area. PL/SQL controls the context area through a cursor. A
cursorholdstherows(oneormore)returnedbyaSQLstatement.Thesetofrowsthecursorholds is referred to as the
activeset.

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 −

 Implicitcursors
 Explicitcursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed,
whenthereisnoexplicitcursorforthestatement.Programmerscannotcontroltheimplicitcursors and the information
init.

Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associatedwiththisstatement.ForINSERToperations,thecursorholdsthedatathatneedstobe inserted. For UPDATE
and DELETE operations, the cursor identifies the rows that would be affected.

InPL/SQL,youcanrefertothemostrecentimplicitcursorastheSQLcursor,whichalwayshas attributes such as


%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−

S.No Attribute & Description

%FOUND

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

2 %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

3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor
automatically after executing its associated SQL statement.

%ROWCOUNT

4 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_nameas shown below in the example.

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

Select * from customers;

+----+----------+-----+-----------+----------+
| ID|NAME | AGE | ADDRESS | SALARY|
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25|Delhi | 1500.00|
| 3 | kaushik | 23|Kota | 2000.00 |
| 4 | Chaitali | 25|Mumbai | 6500.00 |
| 5 | Hardik | 27|Bhopal | 8500.00 |
| 6|Komal | 22|MP | 4500.00|
+----+----------+-----+-----------+----------+

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 −

DECLARE

total_rows
number(2); BEGIN
UPDATE customers
SET salary = salary + 500;

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;
When the above code is executed at the SQL prompt, it produces the following result −
/
6 customers selected

PL/SQL procedure successfully completed.

If you check the records in customers table, you will find that the rows have been updated −

Select * from customers;

+----+----------+-----+-----------+----------+
| ID|NAME | AGE | ADDRESS | SALARY|
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25|Delhi | 2000.00|
| 3 | kaushik | 23|Kota | 2500.00 |
| 4 | Chaitali | 25|Mumbai | 7000.00 |
| 5 | Hardik | 27|Bhopal | 9000.00 |
| 6|Komal | 22|MP | 5000.00|
+----+----------+-----+-----------+----------+

Explicit Cursors
Explicitcursorsareprogrammer-definedcursorsforgainingmorecontroloverthecontextarea.
AnexplicitcursorshouldbedefinedinthedeclarationsectionofthePL/SQLBlock.Itiscreated on a SELECT
Statement which returns more than onerow.

The syntax for creating an explicit cursor is −


CURSOR cursor_name IS select_statement;

EXCERISE – 10

EXCEPTION HANDLING IN PL/SQL


In PL/SQL a warning or error condition is called an exception. Exceptions can be internally defined (by the
runtime system) or user-defined. Examples of internally defined exceptions include division by zero and out of
memory.
Predefined Exceptions

CURSOR_ALREADY_OPEN is raised if you try to OPEN an already open cursor.


DUP_VAL_ON_INDEX is raised if you try to store duplicate values in a database column that is constrained
by a unique index.
INVALID_CURSOR is raised if you try an illegal cursor operation. For example, if you try to CLOSE an
unopened cursor.
INVALID_NUMBER is raised in a SQL statement if the conversion of a character string to a number fails.
LOGIN_DENIED is raised if you try logging on to ORACLE with an invalid username/password.
NO_DATA_FOUND is raised if a SELECT INTO statement returns no rows or if you reference an
uninitialized row in a PL/SQL table.
NOT_LOGGED_ON is raised if your PL/SQL program issues a database call
without being logged on to ORACLE. PROGRAM_ERROR is raised if PL/SQL has an internal problem.
STORAGE_ERROR is raised if PL/SQL runs out of memory or if memory is corrupted.
TIMEOUT_ON_RESOURCE is raised if a timeout occurs while ORACLE is waiting for a resource.
TOO_MANY_ROWS is raised if a SELECT INTO statement returns more than one row.
VALUE_ERROR is raised if an arithmetic, conversion, truncation, or constraint error occurs.
ZERO_DIVIDE is raised if you try to divide a number by zero.

Handling Raised Exception


Syntax :
... EXCEPTION
WHEN ... THEN
- handle the errordifferently WHEN ... OR ... THEN
- handle the errordifferently
...
WHEN OTHERS THEN
- handle the errordifferently END;
1) QB 1 Handling NO_DATA_FOUND and ZERO_DIVIDE Exceptions Declare
n1 number; n2 number;
Begin
n2 := &n2;
Select sal into n1 from emp where empno=7654; n1 := n1/n2;
Exception
whenzero_divide then dbms_output.put_line(‘Zero Divide Error !’); when no_data_found then
dbms_output.put_line(‘No such Row in EMP table’); when others then
dbms_output.put_line(‘Unknown exception’); end;

User Defined Exception


Unlike predefined exceptions, user-defined exceptions must be declared and must be raised explicitly by
RAISE statements. Exceptions can be declared only in the declarative part of a PL/SQL block, subprogram, or
package. You declare an exception by introducing its name, followed by the keyword EXCEPTION.
Exception Declaration
Ex.
DECLARE
past_due EXCEPTION; acct_num NUMBER(5); BEGIN

Exceptions and variable declarations are similar. But remember, an exception is an error condition, not an
object. Unlike variables, exceptions cannot appear in assignment statements or SQL statements.
Syntax.
Exception-name Exception;

Using Raise statement


User-defined exceptions must be raised explicitly by RAISE statements. Syntax
RAISE exception-name;

Q2) Write PL/SQL block to raise ‘out-of-balance’ exception if balance fall below 100. DECLARE
out_of_balance EXCEPTION; bal NUMBER;
BEGIN
IF bal< 100 THEN
RAISE out_of_stock;
END IF;
. EXCEPTION
WHEN out_of_balance THEN
dbms_output.put_line(‘Low balance. Unable to do Transactions’); END;
Raise_Application_Error
This is a procedure to issue user-defined error messages from a stored subprogram or database trigger.
Syntax :raise_application_error(error_number, error_message);
whereerror_number is a negative integer in the range -20000..-20999 and error_message is a character string up
to 512 bytes in length.
Ex. ….
IF salary is NULL THEN
raise_application_error(-20101, 'Salary is missing');
….

EXCERISE – 11

TRIGGERS IN PL/SQL
Triggersarestoredprograms,whichareautomaticallyexecuted orfiredwhensomeeventsoccur. Triggers are, in fact,
written to be executed in response to any of the following events–

 A database manipulation (DML) statement (DELETE, INSERT, orUPDATE)


 A database definition (DDL) statement (CREATE, ALTER, orDROP).
 Adatabase operation(SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).

Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers

Triggers can be written for the following purposes −


 Generating some derived column values automatically
 Enforcing referentialintegrity
 Event logging and storing information on tableaccess
 Auditing
 Synchronous replication oftables
 Imposing securityauthorizations
 Preventing invalidtransactions

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;
Where,
 CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with
thetrigger_name.
 {BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The INSTEAD
OF clause is used for creating trigger on aview.
 {INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DMLoperation.
 [OF col_name] − This specifies the column name that will beupdated.
 [ON table_name] − This specifies the name of the table associated with thetrigger.
 [REFERENCING OLD AS o NEW AS n] − This allows you to refer new and old values for various
DML statements, such as INSERT, UPDATE, andDELETE.
 [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 leveltrigger.
 WHEN (condition) − This provides a condition for rows for which the trigger would fire. This clause is
valid only for row-leveltriggers.

Example
To start with, we will be using the CUSTOMERS table we had created and used in the previous chapters −

Select * from customers;

+----+----------+-----+-----------+----------+
| ID|NAME | AGE | ADDRESS | SALARY|
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25|Delhi |1500.00|
| 3 | kaushik | 23|Kota |2000.00 |
| 4 | Chaitali | 25|Mumbai | 6500.00 |
| 5 | Hardik | 27|Bhopal | 8500.00 |
| 6|Komal | 22|MP | 4500.00|
+----+----------+-----+-----------+----------+

The following program creates a row-level trigger for the customerstable that would fire for
INSERTorUPDATEorDELETEoperationsperformedontheCUSTOMERStable.Thistrigger will display the
salary difference between the old values and new values−

CREATE OR REPLACE TRIGGER display_salary_changes


BEFORE DELETE OR INSERT OR UPDATE ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/

When the above code is executed at the SQL prompt, it produces the following result −

Trigger created.
The following points need to be considered here−
 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 consistentstate.
 The above trigger has been written in such a way that it will fire before any
DELETE or
INSERTorUPDATEoperationonthetable,butyoucanwriteyourtriggeronasingleor
multiple operations, for example BEFORE DELETE, which will fire whenever a
record will be deleted using the DELETE operation on thetable.

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 −

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (7, 'Kriti', 22, 'HP', 7500.00 );

When a record is created in the CUSTOMERS table, the above


create trigger, display_salary_changeswill be fired and it will display the
following result−

Old salary:
New salary: 7500
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
SET salary = salary + 500
WHERE id = 2;

When a record is updated in the CUSTOMERS table, the above


create trigger, display_salary_changeswill be fired and it will display the
following result−
Old salary: 1500
New salary: 2000
Salary difference: 500

GUI SCREEN SHOOTS


ADMIN PANEL: -
MAIN APPLICATION:

You might also like