0% found this document useful (0 votes)
74 views42 pages

ADBMS Manual

The document discusses database concepts including DCL commands, locks, privileges, authorization, authentication, and creating database objects. It provides examples of using the GRANT command to assign privileges to users for accessing tables. The REVOKE command is used to remove privileges. Locks such as explicit locks using the SELECT...FOR UPDATE statement and LOCK TABLE statement are demonstrated. Authorization and authentication are defined, and privileges are explained as rights to perform SQL statements or access other users' objects. Methods of granting and revoking privileges through Oracle are shown using GRANT and REVOKE statements. Finally, examples are given for creating synonyms, sequences, and indexes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views42 pages

ADBMS Manual

The document discusses database concepts including DCL commands, locks, privileges, authorization, authentication, and creating database objects. It provides examples of using the GRANT command to assign privileges to users for accessing tables. The REVOKE command is used to remove privileges. Locks such as explicit locks using the SELECT...FOR UPDATE statement and LOCK TABLE statement are demonstrated. Authorization and authentication are defined, and privileges are explained as rights to perform SQL statements or access other users' objects. Methods of granting and revoking privileges through Oracle are shown using GRANT and REVOKE statements. Finally, examples are given for creating synonyms, sequences, and indexes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

ADBMS (3340701)

Practical:1
AIM:- Perform queries for DCL command and Locks.
DCL Commands are GRANT and REVOKE

GRANT:
Granting privileges means to give permission to some user to access database object or a
part of a database object.
The GRANT command is used to serve this purpose. This command provides various types of
access to database objects such as tables, views and sequences.
Syntax:
GRANT object privileges
ON object name
TO user name
[WITH GRANT OPTION];

Privilege Allows user…


ALL To perform all the operations listed below.
ALTER To change the table structure using ALTER command.
DELETE To delete records from the table using DELETE command.
INDEX To create an index on the table using CREATE INDEX command.
INSERT To insert records into the table using INSERT INTO command.
REFERENCES To reference table while creating foreign keys.
SELECT To query the table using SELECT command.
UPDATE To modify the records in the table using UPDATE command.

Example 1: As a user1,grant yser2 all the data manipulation permissions on the table
customer, with allowing him to pass privileges to other users.
INPUT: GRANT ALL
ON Customer
TO user2
WITH GRANT OPTION;
OUTPUT:
Grant Succeeded.
Example 2: As a user2, grant select and insert privileges to user3.

INPUT: GRANT SELECT, INSERT


ON user1.Customer
TO user3;

OUTPUT: Grant Succeeded.

209590307052 NFDE
ADBMS (3340701)

REVOKE:
Revoking privileges means to deny permission to user given previously.

Syntax:
GRANT object privileges
ON object name
TO user name
[WITH GRANT OPTION];

Example 3: As a user2, revoke the select and insert privileges from user3.

INPUT: REVOKE SELECT, INSERT


ON user1.Customer
From user3;

OUTPUT: Revoke Succeeded.

Locks
“The technique used to protect data when multiple users are accessing it concurrently is
called Concurrency Control.”
Oracle uses a method called ‘locking’ to implement Concurrency Control. In simple words, a
locking means to restrict other users from accessing data temporarily.
Implicit lock
Explicit lock

Explicit locks: In Oracle, user can lock data in a table on its own instead of automatic locking
provided by oracle. Such types of locks are called ‘Explicit Locks’.
1. SELECT …FOR UPDATE Statement

Syntax:
SELECT * FROM tablename FOR UPDATE [NOWAIT];

Description:
 This statement is used to acquire exclusive locks for performing updates
on records.
 Based on the WHERE clause used with SELECT statement, level of lock will
be applied.
 If table is already locked by other user, then this command will simply wait
until that lock is released. But , if NOWAIT is specified, and table is not free,
this command will return with error message indicating “resource is busy”.
 Lock will be released on executing COMMIT or ROLLBACK.

Example 4: As a user1,place an exclusive lock on accounts of ‘vvn’ branch using


SELECT…FOR UPDATE Statement.

209590307052 NFDE
ADBMS (3340701)

SELECT * from Account


WHERE bname = ‘vvn’
FOR UPDATE;

Example 5: As a user2, update balance to 1000 for all accounts of ‘vvn’ branch.

UPDATE Account SET balance = 1000


WHERE bname = ‘vvn’;

2. The Lock Table Statement

Syntax:
LOCK TABLE tablename
IN lockmode MODE [NOWAIT];
Description:
 This statement is used to acquire lock in one of several specified modes on a
given table.
 If NOWAIT is specified, and table is not free, this command will return with
error message indicating “resource is busy”.

Example 6: As a user1,place an exclusive lock on Account table using LOCK TABLE


Statement.

LOCK TABLE ACCOUNT


IN Exclusive MODE NOWAIT;
Example 7: Update the balance for account ‘A01’ to 10000 as a user1.

UPDATE Account SET balance =10000 WHERE ano=’A01’;

209590307052 NFDE
ADBMS (3340701)

Practical:2
AIM:- Implement authorization, authentication, Privileges on
database.
Authorization:
Authorization includes primarily two processes.
 Permitting only certain users to access, process or alter data.
 Applying varying limitations on user access or actions.
o The limitations placed on (or removed from) users can apply to
objects, such as schemas, tables, or rows, or to resources, such as
time.
Privileges:
A privilege is a right to execute a particular type of SQL statement or to access
another user’s object.
Some examples of privileges include the right to:
 Connect to the database.
 Create a table.
 Select rows from another user’s table.
 Execute another user’s stored procedure.
You grant privileges to users so these users can accomplish tasks required for their jobs. You
should grant a privileges only to a user who requires that privilege to accomplish the necessary
work.
Excessive granting of unnecessary privileges can compromise security. A user can receive a
privilege in two different ways:
You can grant privileges to users explicitly. For example, you can explicitly grant users
SCOTT the privilege to insert records into the employees table.
You can also grant privileges to a role, and then grant the role to one or more users.
For example, you can grant the privileges to select, insert, update and delete
records from the employee table to the role named clerk, which in turn you can grant to users
Scott.

Oracle/PLSQL: Grant/Revoke Privileges


You can grant and revoke privileges on various database objects in oracle.
Granting a Privileges
Example:-
For example, if you wanted to grant SELECT, INSERT, UPDATE and
DELETE privileges on a table called Suppliers to a user name, smith, you would
run the following GRANT statement.
GRANT SELECT, INSERT, UPDATE, DELETE
ON Suppliers
TO smith;

209590307052 NFDE
ADBMS (3340701)

You can also use the ALL Keyword to indicate that you wish ALL permissions to be
granted for a username smith.
For ex:- GRANT ALL
ON Suppliers
TO smith;

If you wanted to grant only SELECT access on your table to all users, you could grant the
privileges to the public keyword.
For ex:- GRANT SELECT
ON Suppliers
TO public;

Revoking a Privileges
Example:
For example, if you wanted to revoke DELETE privileges on a
table called Suppliers from a user named Anderson.

You would run the following REVOKE Statement.


Revoke Delete
ON suppliers
From Anderson;

If you wanted to revoke ALL privileges on a table for a user named


Anderson, you could use the ALL keyword as follows:

Revoke ALL
ON suppliers
From Anderson;

If you had granted ALL privileges to public on the suppliers table and
you wanted to revoke these privileges, you could run the following
revoke statement,

Revoke ALL
ON suppliers
From public;

209590307052 NFDE
ADBMS (3340701)

Practical:3
AIM:- Perform queries to create synonyms, sequence and index.
Synonyms:
“A Synonym is an alias or alternative name for database objects such as tables,
views, indexes, sequences”
A Synonym can be used to hide the actual identity of the object being referenced.
Creating a Synonym:
Syntax:
Create synonym synonymName
For objectname;

Example 1: As a user 2, create a Synonym for Customer table owned by user1.

INPUT: create synonym cust


For user1.Customer;

OUTPUT: Synonym Created.

Destroying a Synonym

Syntax:
DROP Synonym synonymName ;

Sequence:
“A Sequence is simply an automatic counter, which generates sequential numbers
whenever required.”
The value generated by a Sequence can be used in insert and update operations. A
value generated can have a maximum of 38 digits.
Syntax:
CREATE SEQUENCE sequenceName
[START WITH n
INCREMENT BY n
MINVALUE n / NOMINVALUE
MAXVALUE n / NOMAXVALUE
CYCLE / NOCYCLE
CACHE n / NOCACHE
ORDER / NOORDER];

Option Specifies…..
START WITH Specifies the first sequence number. Default for the ascending sequence is
the minimum value 1 . Default value for the descending sequence is
maximum value -1.
INCREMENT Specifies the interval between sequence numbers.It can be any positive or
BY negative number, but not zero.Default value is 1.
MINVALUE Specifies the sequence minimum value.

209590307052 NFDE
ADBMS (3340701)

MAXVALUE Specifies the sequence maximum value.


CYCLE Specifies to repeat cycle of generating values after reaching maximum value
CACHE Specifies how many values to generate in advance and to keep in memory
faster access. Minimum value is two for this option.
ORDER Guarantees that sequence numbers are generated in order. This is only used
while using parallel servers in parallel mode.

Example 2: Create a Sequence which generates number from 1 to 99 in ascending order


and stops after generating number 99.
Input: Create sequence
mySequence start with 1
increment by 1
minvalue 1
maxvalue 1
nocycle;

Output: Sequence Created.

Destroying a Sequence

A sequence can be destroyed as described below.

Syntax:
Drop Sequence sequenceName;

Example 3: Drop this sequence ‘mySequence’ created

above. Input: DROP sequence mySequence;

Output: Sequence dropped.

Index:
“An index is an ordered list of contents of the column of a table.”
Syntax:
Create [unique] INDEX indexName
ON tableName (columnName);

Example 4: Create Simple index on ‘name’ column of a Customer table.


INPUT: Create INDEX indCustName
ON Customer (name);

OUTPUT: Index Created.


Destroying a Index
Syntax:
Drop INDEX indexName;

209590307052 NFDE
ADBMS (3340701)

Example 3: Drop this index ‘indCustName’ created above.

Input: DROP INDEX indCustName;

Output: Index dropped.

209590307052 NFDE
ADBMS (3340701)

Practical:4
AIM:- Perform queries to create, alter and update Views.
Views:
“A View is a virtual or logical table that allows to view or manipulate parts of the tables.”
Syntax:
CREATE [OR REPLACE] VIEW viewName
AS SELECT….
[WITH READ ONLY];

Description:
 This Statement creates a view based on query specified in SELECT statement.
 OR Replace option re-creates the view if it is already existing maintaining the privileges
granted to view ViewName.
 WITH READ ONLY option creates read-only views. IF this option is not provided, by
default, updateable views are created.
 The SELECT statement can include WHERE, ORDER BY, GROUP BY clauses if
required.
 A view can be created using single base table, as well as multiple base tables using joins.
A View using Single Base Table:
Example 1: Create a view ‘Acc_vvn’ based on Account table to have only accounts
belonging to ‘vvn’ branch.
Input: CREATE VIEW Acc_vvn
AS SELECT * FROM Account,
WHERE bname=’vvn’;
OUTPUT: View Created.

Example 2: Display all the accounts from Acc_vvn view.


INPUT: SELECT * FROM Acc_vvn.
OUTPUT: ANO BALANCE BNAME
A01 5000 vvn
A02 6000 vvn

A View using Multiple Base Table:


Example 3: Create a view ‘Acc_Branch’ based on Account and Branch table having all
the information about accounts and related branches.
INPUT: CREATE VIEW Acc_Branch
AS SELECT ano, balance, Account.bname, Branch.baddress
FROM Account, Branch
WHERE Account.bname = Branch.bname;

OUTPUT: View created.


Example 4: Display consistent information about accounts and its branches using
Acc_Branch view.

209590307052 NFDE
ADBMS (3340701)

INPUT: SELECT * FROM Acc_Branch;


OUTPUT: ANO BALANCE BRANCH BADDRESS
A01 5000 vvn Mota bazaar,VVNagar
A02 6000 ksad Chhota bazaar, Karamsad
A03 7000 anand Nana bazaar, Anand

Destroying a View
Syntax:
DROP VIEW viewName;
Desciption:
 The DROP VIEW command drops the specified view.
 The base tables will not be affected if a view is destroyed.
Example 5: Drop the view
Acc_Branch. INPUT: DROP VIEW
Acc_Branch; OUTPUT: View dropped.

209590307052 NFDE
ADBMS (3340701)

Practical:5
AIM:- Implement PL/SQL programs using control structure.
In PL/SQL, the flow of execution can be controlled in three different manners as given below:
1. Conditional Control.
2. Iterative Control.
3. Sequential Control.

Conditional Control
The IF-THEN-ELSEIF-END IF construct can be used to execute specific part of the
block based on the conditions provided.
Syntax:
IF condition THEN
--Execute commands…
ELSEIF condition THEN
--Execute commands…
.
.
.
.
.
ELSE --Execute commands…
END IF;
Example 1: Write a program to read a number from user and determine whether it is odd or even.
INPUT:
DECLARE
No Number;
BEGIN
no := &no;
IF MOD (no,2) = 0 THEN
Dbms_output.put_line(‘Given number’|| no || ‘ is EVEN.’);
ELSE
Dbms_output.put_line(‘Given number’|| no || ‘ is ODD.’);
END IF;
END;
/

Iterative Control
Iterative control allows a group of statements to execute repeatedly in a program.
1. LOOP
2. WHILE
3. FOR

1. LOOP
Syntax:

209590307052 NFDE
ADBMS (3340701)

LOOP

209590307052 NFDE
ADBMS (3340701)

--Execute commands…
END LOOP
 Loop is an infinite loop. It executes commands in its body infinite times.
 So, it requires an EXIT statement within its body to terminate the loop after
executing specific iterations.

2. WHILE
 The WHILE loop executes commands in its body as long as the condition
remains TRUE.
 The loop terminates when the condition evaluates to FALSE or NULL.
 The EXIT statement can also be used to exit the loop.

Syntax:
WHILE condition
LOOP
--Execute commands…
END LOOP
 The WHILE loop executes commands in its body as long as the condition
remains TRUE.
 The loop terminates when the condition evaluates to FALSE or NULL.
 The EXIT statement can also be used to exit the loop.
3. FOR
Syntax:
FOR variable IN [REVERSE] start .. end
LOOP
--Execute commands…
END LOOP
 The FOR loop can be used when the number of iterations to be executed are known.
 Here, a variable is a loop control variable. It is declared implicitly by PL/SQL. So
it should not be declared explicitly.
 The FOR loop variable is always incremented by 1, and any other increment value
cannot be specified.
 A start and end specifies the lower and upper bound for the loop control variable.
 If REVERSE keyword is provided, loop is executed in reverse order, i.e. from end to
start.

Example 2: Display numbers from 1 to 10 along with their square values using WHILE
construct.
INPUT:
BEGIN
Dbms_output.put_line(‘value’|| ‘square’);
FOR counter IN 1 .. 10
LOOP
Dbms_output.put_line(‘ ‘ || counter|| ‘ ‘ || counter * counter);
END LOOP;
209590307052 NFDE
ADBMS (3340701)

END;
/

Sequential Control
Syntax:
GOTO jumpHere;
.
.
.
.
.
<< jumpHere>>
 The GOTO statement makes flow of execution to jump at <<jumpHere>>.
 This jump is unconditional.
 The GOTO statement is not an essential element in developing a successful
program code.

209590307052 NFDE
ADBMS (3340701)

Practical:6
AIM:- Implement PL/SQL programs using cursors.
Cursors:
“A cursor is an area in memory where the data required to execute SQL statement is
stored.”
The data that is stored in the cursor is called the Active Data Set. So, the size of the
cursor will be same as a size to hold this data. As this data is stored due to execution of
some SQL statement, it is also called the Result Set.
The row that is being processed is called the Current Row. A pointer, known as a Row
Pointer, is used to track the current row. It is updated to point to the next row, each
time a current row is processed.
Along with this, multiple cursor variables are used to indicate the current status of the
processing being done by the cursor. Such kind of variables are known as Cursor
Attributes.
Attribute Name Description
%ISOPEN If cursor is open, returns TRUE; ELSE, returns FALSE.
%FOUND If cursor was fetched successfully, returns TRUE; ELSE, returns
FALSE.
%NOTFOUND If record was not fetched successfully, returns TRUE;ELSE returns
FALSE.
%ROWCOUNT Returns number of records processed by the Cursor.

Cursors can be classified into one of the two categories, based on how they are opened .
1. Implicit Cursors, and
2. Explicit Cursors.

Implicit Cursors
“A cursor is called an Implicit Cursor, if it is opened by Oracle itself to execute any
SQL statement.”

The Syntax to use attributes of implicit cursor can be given as-

SQL.AttributeName
Example 1: In Account table, branch names are stored in lower case letters. Convert
branch name into upper case letters for a branch specified by the user. Also,
display how many accounts are affected.

INPUT:
Declare
Branch Account.bname%TYPE;
Begin

Branch:= &branch;
UPDATE Account SET bname = UPPER(branch)
Where bname=branch;

209590307052 NFDE
ADBMS (3340701)

IF SQL%FOUND THEN
Dbms_output.put_line(‘Total’ || SQL%ROWCOUNT || ‘
records are updated…..’);

Else
Dbms_output.put_line(‘Given branch not available…..’);
END IF;
END;
/
OUTPUT:
Enter value for branch:’surat’
Old 6:branch := &branch;
New 6:branch := ‘surat’
Given branch not available…

Explicit Cursors
“A cursor is called an Explicit Cursor, if it is opened by user to process
data through PL/SQL block.”

The Steps required to manage explicit cursors and manipulate data are
given below:

1. Declare a Cursor.
2. Open a Cursor.
3. Fetching Data.
4. Processing Data.
5. Closing Cursor.
1. Declare a Cursor
A Cursor is defined in the declaration section of the PL/SQL block using
following syntax.
Syntax:
CURSOR cursorName IS SELECT…..;
Description:
 A cursor with cursorName is declared.
 It is mapped to the query given by SELECT statement.
2. Open a Cursor
A Cursor can be opened using OPEN statement as described below. While
opening a cursor following operations are performed. These operations initialize
the given cursor:
 Allocate memory required to store data.
 Execute the SELECT statement associated with cursor.
Syntax:
OPEN cursorName;
3. Fetching Data

209590307052 NFDE
ADBMS (3340701)

Syntax:

209590307052 NFDE
ADBMS (3340701)

FETCH cursorName INTO variable1, variable2… ;


Description:
 Retrieves data from the current row in the active data set and stores
them in given variables.
 Data from single row are fetched at a time.

4. Processing Data
This step involves actual processing of the table data. Data are already fetched
into variables, and these variables can be processed as per requirements .
5. Closing Cursor
A Cursor should be closed after the processing of data completes.
Syntax:
CLOSE cursorName;

Example 2: Transfer all the accounts belonging to ‘vvn’ branch from Account table into
another table ‘Acc_vvn’ having only 2 columns acc_no & balance.
INPUT:
Declare
CURSOR cAcc IS SELECT ano, balance, bname FROM Account;
No Account.ano%TYPE;
Bal Account.balance%TYPE;
Branch Account.bname%TYPE;
Begin
OPEN cAcc;
IF cAcc%ISOPEN THEN
LOOP
Fetch cAcc INTO no,bal,branch;
EXIT WHEN cAcc%NOTFOUND;
IF branch = ‘vvn’ THEN
INSERT INTO Acc_vvn VALUES(no,bal);
DELETE FROM Account WHERE ano=no ;
END IF;
END LOOP;
COMMIT;
ELSE
Dbms_output.put_line(‘Cursor cannot be opened…..’);
END IF;
END;
/

209590307052 NFDE
ADBMS (3340701)

Practical:7
AIM:- Implement PL/SQL programs using Exception Handling.
Exception:
An exception is a run-time anomaly or unusual condition that a program may
encounter while executing.

Syntax:
EXCEPTION
WHEN exceptionName THEN
-- Code to Handle Exception. . . . .
Named Exception
Declare
No Account.ano%TYPE;
Bal Account.balance%TYPE;
Branch Account.bname%TYPE;
BEGIN
No :=&no;
Bal :=&bal;
Branch :=&branch;
INSERT INTO Account values(no, bal, branch);
COMMIT;
Dbms_output.put_line(‘Record inserted successfully’);
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
Dbms_output.put_line(‘Duplicate value found for Primary key.’);
END;
/

OUTPUT 1:
Enter value for no: ‘A01’
Enter value for bal: 5000
Enter value for branch: ‘vvn’
Record inserted successfully…
OUTPUT 2:
Enter value for no: ‘A01’
Enter value for bal: 10000
Enter value for branch: ‘ksad’
Duplicate value found for primary key

Numbered Exception
Syntax:
Declare
exceptionName EXCEPTION;
PRAGMA EXCEPTION_INIT (exceptionName, errorNumber);
Begin
- - Execute Commands. . .
209590307052 NFDE
ADBMS (3340701)

Exception
WHEN exceptionName THEN
--Code to Handle Exceptio . . . . .
End;
/
Description:
o An exception is declared in declaration section.
o A PRAGMA is a call to pre-compiler that binds the numbered
exception to some name.
o A function EXCEPTION_INIT takes two parameters: one is exception
name, and other is number of the exception to be handled.
o Once binding is provided, exception can be handled in exception handling
section using WHEN clause.
User-defined Exception
Syntax:
Declare
exceptionName EXCEPTION;
BEGIN
IF condition THEN
RAISE exceptionName
END IF;
EXCEPTION
WHEN exceptionName THEN
--Code to Handle Exception . . . .
END;
/
Description:
o A user defined exception need to be declared in Declaration section.
o A RAISE clause raises an exception, and transfers control of execution
from Executable Commands section to Exception Handling section.
o This exception can be handled in exception handling section like as
named and numbered exceptions.

209590307052 NFDE
ADBMS (3340701)

Practical:8
AIM:- Implement PL/SQL programs using Procedures and
Functions.
A procedure or function is a group or set of SQL and PL/SQL statements
that perform a specific task.
Creating a Procedure
Syntax:
Create or Replace Procedure procedureName
(argument [ IN OUT, IN OUT] dataType, ….)
IS
<Declaration Section>
Begin
<Executable Commands>
Exception
<Exception Handling>
End;

Keyword Specifies…..
Create Creates a specified object, here a procedure.
Replace Re-creates the procedure , if it is already existing, maintaining the
privileges granted to procedure procedureName.
IN Specifies that a value must be passed for this argument while
invoking or calling procedure.
OUT Specifies that a procedure returns a value for this argument in its
calling environment.
IN OUT This is the combination of IN and OUT.

Example 1: Create a procedure debitAcc which debits a given account with


specified amount.
Create or Replace Procedure debitAcc
(no IN Account.ano%TYPE, amount IN NUMBER)
IS
Bal Account.balance%TYPE;
newBalance Account.balance%TYPE;
Begin
SELECT balance INTO bal FROM Account
WHERE ano:=no;
newBalance := bal-amount;
UPDATE Account SET balance = newBalance
WHERE ano = no;
Dbms_output.put_line(‘Account’|| no || ‘debited…..’);
End;

/
209590307052 NFDE
ADBMS (3340701)

OUTPUT:
Procedure Created.
Creating a Function
Syntax:
Create or Replace Function functionName
(argument IN dataType, ….)
Return dataType
IS
<Declaration Section>
Begin
<Executable Commands>
Exception
<Exception Handling>
End;

Keyword Specifies…..
Create Creates a specified object, here a function.
Replace Re-creates the function , if it is already existing, maintaining
the privileges granted to function functionName.
IN Specifies that a value must be passed for this argument while
invoking or calling function.
OUT Specifies that a function will returns a value having data type
datatype.

Example 2 : Create a function getbalance which returns the balance for the given
account.
INPUT:
Create or Replace Function getbalance
(no IN Account.ano%TYPE)
Return NUMBER
IS
Bal Account.balance%TYPE;
Begin
SELECT balance INTO bal FROM Account
WHERE ano:=no;
Return bal;
End;
/
OUTPUT:
Function created.

209590307052 NFDE
ADBMS (3340701)

Practical:9
AIM:- Perform Various operations on Package.
“A package is a container for other database object.”A package can hold other
database object such as variables, constants, cursors, exception, procedures,
functions and sub-programs.
A package contain two contain section:
1) Package specification
2) Package Body
1. Package specification
Various object to be help by package are declare in this section. Objects may involve variable,
constant, exception, procedure, and functions.
Syntax:
CREATE OR REPLACE PACKAGE PACKAGENAME
IS

_ _ _ _ _package specification. . . . .
END packageName;

Example1 :Create a package transaction that contains procedure


‘debit Acc’ and function ‘Get Balance’ create earlier.
Input:
CREATE OR REPLACE PACKAGE TRANSACTION
IS
Procedure debitAcc (no IN account.ano%TYPE, amount IN
NUMBER); FUNCTION getBalance ( no IN Account.ano%TYPE)
return number ; END transaction;

Output: package created.


2.Package body
The package body contains the formal definition of all the objects referenced in the
specific selection.
Package body is created using command CREATE PACKAGE BODY as given
below:

Syntax:
CREATE OR REPLACE PACKAGE BODY PACKAGE/NAME
IS
---package body. . . . .
END packageName;

Example 2: Create a package body for package transaction that contains


procedure ‘debitAcc’ and function ‘getBalance’ created earlier.

209590307052 NFDE
ADBMS (3340701)

INPUT:

209590307052 NFDE
ADBMS (3340701)

Create or replace package body transaction


IS
Procedure debitAcc(no IN Account.ano%TYPE, amount IN number)
IS
Bal Account.balance%TYPE;
newBalance Account.balance %TYPE;

Begin
Select balance INTO bal FROM Account
Where ano:= no;
newBalance := bal – amount;
UPDATE Account SET balance = newBalance
Where ano = no;
Dbms_output.put_line(‘Account’ || no || ‘debited’);
END;
FUNCTION getBalance (no IN Account.ano%TYPE) Return NUMBER
IS
Bal Account.balance%TYPE;
Begin
Select balance INTO bal FROM Account
Where ano = no;
RETURN bal;
END;
END transaction;
/
OUTPUT: Package body created.

209590307052 NFDE
ADBMS (3340701)

Practical:10
AIM:- Implement various triggers.
“A trigger is a group or set of SQL and PL/SQL statements that are executed by
Oracle itself.”
Creating a Trigger
A trigger can be created using following syntax:
Syntax:
Create or replace trigger
triggerName [BEFORE/AFTER]
[INSERT, DELETE, UPDATE [OF COLOUMN] ]
ON tableName
[REFERENCING [OLD as old, NEW as new] ]
[FOR EACH ROW [WHEN condition ] ]
Declare
<Declaration Section>
Begin
<Executable Commands>
Exception
<Exception Handling>
END;

Keyword Specifies…..
REPLACE Re-creates the trigger if it already exists.
BEFORE Creates BEFORE type trigger.
AFTER Creates AFTER type trigger.
DELETE Indicates that trigger will be fired on DELETE operation.
INSERT Indicates that trigger will be fired on INSERT operation.
UPDATE Indicates that trigger will be fired on UPDATE operation.
ON Specifies table for which trigger is defined.
REFERENCING Specifies correlation names – OLD and NEW – that specify old an new
value for a record during triggering statement.
FOR EACH ROW Creates ROW type trigger. If omitted, STATEMENT type trigger is
created.
WHEN Specifies condition as a trigger restriction.

Example 1: Using trigger, display message if balance is negative during insert operation on
Account table.

INPUT:
Create or Replace Trigger balNegative
BEFORE INSERT
ON Account
FOR EACH ROW
BEGIN
IF :NEW.balance < 0 THEN
Dbms_output.put_line(‘Balance is in Negative…..’);

209590307052 NFDE
ADBMS (3340701)

END IF;
END;
/
OUTPUT: Trigger created.

Example 2: Insert a new Record in Account table having balance -5000, i.e. some negative
value.

INPUT:
INSERT INTO Account VALUES (‘A01’,-5000, ‘vvn’);

OUTPUT:
Balance is in Negative…..
1 row created

Destroying a Trigger
A trigger can be destroyed using following synatax:
Syntax:
DROP TRIGGER triggerName;
Example 3: Drop Trigger balNegative;

OUTPUT: Trigger dropped.

209590307052 NFDE
ADBMS (3340701)

Practical:11
AIM:- Practices on Functional Dependencies.
Functional Dependency:
Functional dependency is a relationship that exists when one attribute uniquely
determines another attribute.
If R is a relation with attributes X and Y, a functional dependency between the attributes is
represented as X->Y, which specifies Y is functionally dependent on X. Here X is a determinant
set and Y is a dependent attribute. Each value of X is associated precisely with one Y value.
Functional dependency in a database serves as a constraint between two sets of attributes.
Defining functional dependency is an important part of relational database design and contributes
to aspect normalization.

Functional dependency defines Boyce-Codd normal form and third normal form..
Functional dependency is related to a candidate key, which uniquely identifies a tuple and
determines the value of all other attributes in the relation. In some cases, functionally
dependent sets are irreducible if:

 The right-hand set of functional dependency holds only one attribute


 The left-hand set of functional dependency cannot be reduced, since this may change
the entire content of the set
 Reducing any of the existing functional dependency might change the content of the set.

Fully Functional Dependency –


A functional dependency P → Q is full functional dependency if removal of any attribute A from
P means that the dependency does not hold any more. or
In a relation R, an attribute Q is said to be fully functional dependent on attribute P, if it is
functionally dependent on P and not functionally dependent on any proper subset of P. The
dependency P → Q is left reduced, their being no extraneous attributes in the left hand side of
the dependency.
If AD → C, is fully functional dependency, then we cannot remove A or D. i.e. C is fully
functional dependent on AD. If we are able to remove A or D, then it is not full functional
dependency.
Another Example, Consider the following Company Relational Schema,

209590307052 NFDE
ADBMS (3340701)

FIG 1

{SSN, PNUMBER} → HOURS is a full FD since neither SSN → HOURS

nor PNUMBER → HOURS hold

{SSN, PNUMBER} → ENAME is not a full FD (it is called a partial

dependency ) since SSN → ENAME also holds

209590307052 NFDE
ADBMS (3340701)

Practical:12
AIM:- Practice on normalization-using any database perform
various normal forms.
Normalization is a process of organizing the data in database to avoid data
redundancy, insertion anomaly, update anomaly & deletion anomaly.
First normal form (1NF)
As per the rule of first normal form, an attribute (column) of a table cannot hold multiple values.
It should hold only atomic values.

Example: Suppose a company wants to store the names and contact details of its employees.
It creates a table that looks like this:

emp_id emp_name emp_address emp_mobile

101 Herschel New Delhi 8912312390

8812121212
102 Jon Kanpur

9900012222

103 Ron Chennai 7778881212

9990000123
104 Lester Bangalore 8123450987

Two employees (Jon & Lester) are having two mobile numbers so the company stored them in

209590307052 NFDE
ADBMS (3340701)

the same field as you can see in the table above.

209590307052 NFDE
ADBMS (3340701)

This table is not in 1NF as the rule says “each attribute of a table must have atomic (single)
values”, the emp_mobile values for employees Jon & Lester violates that rule.

To make the table complies with 1NF we should have the data like this:

emp_id emp_name emp_address emp_mobile

101 Herschel New Delhi 8912312390

102 Jon Kanpur 8812121212

102 Jon Kanpur 9900012222

103 Ron Chennai 7778881212

104 Lester Bangalore 9990000123

104 Lester Bangalore 8123450987

Second normal form (2NF)


A table is said to be in 2NF if both the following conditions hold:

 Table is in 1NF (First normal form)


 No non-prime attribute is dependent on the proper subset of any candidate key of table.

209590307052 NFDE
ADBMS (3340701)

An attribute that is not part of any candidate key is known as non-prime attribute.

Example: Suppose a school wants to store the data of teachers and the subjects they teach. They
create a table that looks like this: Since a teacher can teach more than one subjects, the table can
have multiple rows for a same teacher.

teacher_id subject teacher_age

111 Maths 38

111 Physics 38

222 Biology 38

333 Physics 40

333 Chemistry 40

teacher_id teacher_age

209590307052 NFDE
ADBMS (3340701)

111 38

222 38

333 40

Candidate Keys: {teacher_id, subject}


Non prime attribute: teacher_age

The table is in 1 NF because each attribute has atomic values. However, it is not in 2NF because
non prime attribute teacher_age is dependent on teacher_id alone which is a proper subset of
candidate key. This violates the rule for 2NF as the rule says “no non-prime attribute is
dependent on the proper subset of any candidate key of the table”.

To make the table complies with 2NF we can break it in two tables like this:
teacher_details table:

teacher_subject table:

teacher_id subject

111 Maths

111 Physics

209590307052 NFDE
ADBMS (3340701)

222 Biology

333 Physics

333 Chemistry

Now the tables comply with Second normal form (2NF).

Third Normal form (3NF)


A table design is said to be in 3NF if both the following conditions hold:

 Table must be in 2NF


 Transitive functional dependency of non-prime attribute on any super key should be
removed.

An attribute that is not part of any candidate key is known as non-prime attribute.

In other words 3NF can be explained like this: A table is in 3NF if it is in 2NF and for each
functional dependency X-> Y at least one of the following conditions hold:

 X is a super key of table


 Y is a prime attribute of table

An attribute that is a part of one of the candidate keys is known as prime attribute.

Example: Suppose a company wants to store the complete address of each employee, they
create a table named employee_details that looks like this:

emp_id emp_name emp_zip emp_state emp_city emp_district

209590307052 NFDE
ADBMS (3340701)

1001 John 282005 UP Agra Dayal Bagh

1002 Ajeet 222008 TN Chennai M-City

1006 Lora 282007 TN Chennai Urrapakkam

1101 Lilly 292008 UK Pauri Bhagwan

1201 Steve 222999 MP Gwalior Ratan

Super keys: {emp_id}, {emp_id, emp_name}, {emp_id, emp_name, emp_zip}…so on


Candidate Keys: {emp_id}
Non-prime attributes: all attributes except emp_id are non-prime as they are not part of any
candidate keys.

Here, emp_state, emp_city & emp_district dependent on emp_zip. And, emp_zip is dependent on
emp_id that makes non-prime attributes (emp_state, emp_city & emp_district) transitively
dependent on super key (emp_id). This violates the rule of 3NF.

To make this table complies with 3NF we have to break the table into two tables to remove the
transitive dependency:

employee table:

209590307052 NFDE
ADBMS (3340701)

emp_id emp_name emp_zip

1001 John 282005

1002 Ajeet 222008

1006 Lora 282007

1101 Lilly 292008

1201 Steve 222999

209590307052 NFDE
ADBMS (3340701)

employee_zip table:

emp_zip emp_state emp_city emp_district

282005 UP Agra Dayal Bagh

222008 TN Chennai M-City

282007 TN Chennai Urrapakkam

292008 UK Pauri Bhagwan

222999 MP Gwalior Ratan

209590307052 NFDE
ADBMS (3340701)

Practical:13
AIM:- Practice on transaction processing.

A transaction can be defined as a group of tasks. A single task is the minimum processing unit
which cannot be divided further.

Let’s take an example of a simple transaction. Suppose a bank employee transfers Rs 500 from
A's account to B's account. This very simple and small transaction involves several low-level
tasks.

A’s Account
Open_Account(A)
Old_Balance =
A.balance
New_Balance = Old_Balance - 500
A.balance = New_Balance
Close_Account(A)
B’s Account
Open_Account(B)
Old_Balance =
B.balance
New_Balance = Old_Balance + 500
B.balance = New_Balance
Close_Account(B)

ACID Properties
A transaction is a very small unit of a program and it may contain several lowlevel tasks. A
transaction in a database system must maintain Atomicity, Consistency, Isolation,
and Durability − commonly known as ACID properties − in order to ensure accuracy,
completeness, and data integrity.

 Atomicity − This property states that a transaction must be treated as an atomic unit, that
is, either all of its operations are executed or none. There must be no state in a database
where a transaction is left partially completed. States should be defined either before the
execution of the transaction or after the execution/abortion/failure of the transaction.

 Consistency − The database must remain in a consistent state after any transaction. No
transaction should have any adverse effect on the data residing in the database. If the
database was in a consistent state before the execution of a transaction, it must remain
consistent after the execution of the transaction as well.

209590307052 NFDE
ADBMS (3340701)

 Durability − The database should be durable enough to hold all its latest updates even if
the system fails or restarts. If a transaction updates a chunk of data in a database and
commits, then the database will hold the modified data. If a transaction commits but the
system fails before the data could be written on to the disk, then that data will be
updated once the system springs back into action.

 Isolation − In a database system where more than one transaction are being executed
simultaneously and in parallel, the property of isolation states that all the transactions
will be carried out and executed as if it is the only transaction in the system. No
transaction will affect the existence of any other transaction.

States of Transactions
A transaction in a database can be in one of the following states −

 Active − In this state, the transaction is being executed. This is the initial state of every
transaction.

 Partially Committed − When a transaction executes its final operation, it is said to be in


a partially committed state.

 Failed − A transaction is said to be in a failed state if any of the checks made by the
database recovery system fails. A failed transaction can no longer proceed further.

 Aborted − If any of the checks fails and the transaction has reached a failed state, then
the recovery manager rolls back all its write operations on the database to bring the
database back to its original state where it was prior to the execution of the transaction.
Transactions in this state are called aborted. The database recovery module can select

209590307052 NFDE
ADBMS (3340701)

one of the two operations after a transaction aborts −

209590307052 NFDE
ADBMS (3340701)

o Re-start the transaction


o Kill the transaction
 Committed − If a transaction executes all its operations successfully, it is said to be
committed. All its effects are now permanently established on the database system.

209590307052 NFDE

You might also like