Dbms Lab Record
Dbms Lab Record
YEAR : II
SEMESTER : IV
2
BONAFIDE CERTIFICATE
Certified that this is a Bonafide Record of Practical Work done by Mr SURENDAR.S…………of B.E .
……………………CSC…………………………… in CS8481 – DATABASE MANAGEMENT SYSTEMS
INDEX
S. No DATE NAME OF THE EXPERIMENTS Page No
1. 24.02.2021 Implementation of Data Definition Language 4
2. 03.03.2021 Implementation of Data Manipulation Language 8
3. 10.03.2021 Implementation of Nested Queries in SQL 19
4. 24.03.2021 Implementation of Join Operations in SQL 26
Implementation of Views, Synonyms, Sequence,
5. 31.03.2021 37
Indexes, Save point
6. 07.04.2021 Implementation of Implicit and Explicit Cursors 44
7. 21.04.2021 Implementation of Integrity Constraints 47
8. 28.04.2021 Study of PL / SQL Block 57
Implementation of Programming Language
9. 28.04.2021 69
Extensions to Satisfy Conditions
Implementation of Procedures and Functions in
10. 12.05.2021 77
PL/SQL
11. 12.05.2021 Implementation of Triggers in SQL 89
Implementation of PL / SQL Blocks - Handling
12. 24.05.2021 93
Exceptions
Implementation of Library Information System
13. 24.05.2021 99
using VB
Implementation of Student Information System
14. 26.05.2021 112
using VB
15. 26.05.2021 Implementation of Simple calculator using VB 122
4
Ex. No: 1
Data Definition Language
Date: 24.02.2021
Aim
To write SQL Statements using Data Definition Language (DDL) to create, alter, truncate and
drop table.
Description:
Creating a table
These commands will primarily be used by database administrators during the setup and
removal phases of a database project.
Table created.
SQL>desc stud;
Name Null? Type
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(2)
SAREA VARCHAR2(20)
ALTER TABLE
Table altered.
SQL>desc stud;
Name Null? Type
----------------------------------------------------- -------- --------------------------------
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)
Table altered.
SQL>desc stud;
Name Null? Type
SAGE NUMBER(10)
SAREA VARCHAR2(20)
SDEPT VARCHAR2(20)
Table altered.
SQL>desc studs;
6
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)
TRUNCATE TABLE
TRUNCATE TABLE removes all rows from a table, but the table structure and its columns,
constraints, indexes and so on remain.
SQL>desc studs;
SNAME VARCHAR2(30)
SID VARCHAR2(10)
SAGE NUMBER(10)
SAREA VARCHAR2(20)
SDEPT VARCHAR2(20)
DROP TABLE
DROP TABLE removes one or more table definitions completely from the database,by
removing all data, indexes, triggers, constraints, and permission specifications for
those tables.
Table dropped.
7
Result
Thus the Data Definition Language (DDL) statements were successfully implemented.
8
Ex. No: 2
Data Manipulation Language
Date: 3-3-2021
Aim
To write Insert, Select, Update, and Delete Commands in Data Manipulation Language (DML)
using SQL
COMMANDS
CREATION OF TABLE
Table created.
INSERTION OF VALUES INTO THE TABLE
Syntax:
1 row created.
1 row created.
1 row created.
SQL> select * from stud;
9
ARITHMETIC OPERATION
------------------------------ ---------
ashwin 201
bhavesh 202
pruthvik 203
charith 204
CONCATENATION OPERATOR
SQL> select sname || ' is a ' || sdept || ' engineer. ' AS "PROFESSION" from studs;
PROFESSION
-------------------------------------------------------------------
studs; SAREA
--------------------
annanagar
kilpauk
nungambakkam
SNAME SAGE
------------------------------ ---------
ashwin 19
bhavesh 18
BETWEEN OPERATOR
SQL> select sname,sarea, sid from studs where sid between 102 and 104;
pruthvikannanagar 103
charithkilpauk 104
IN PREDICATE
SQL> select sname,sarea , sid from studs where sid in(102,104);
bhaveshnungambakkam 102
charithkilpauk 104
PATTERN MATCHING
SQL> select sname, sarea from studs where sarea like '%g%';
SNAME SAREA
------------------------------ --------------------
ashwinannanagar
11
bhaveshnungambakkam
pruthvikannanagar
SQL> select sname ,sid from studs where sid>102 and sarea='annanagar';
SNAME SID
------------------------------ ----------
pruthvik 103
LOGICAL OR OPERATOR
SQL> select sname ,sid from studs where sid>102 or sarea='annanagar';
SNAME SID
------------------------------ ----------
ashwin 101
pruthvik 103
charith 104
NOT IN PREDICATE
SQL> select sname, sid from studs where sid not in(102,104);
SNAME SID
------------------------------ ----------
ashwin 101
pruthvik 103
Table altered.
1 row updated.
1 row updated.
1 row updated.
1 row updated.
SPOCKET
--------------------
RESULT
------------
400
SQL> select resu from studs;
min(spocket) lt
RESULT
-------------
100
13
NUMERIC FUNCTIONS
-------------
20
---------
1024
dual;
RESULT
---------
15.36
---------
6
STRING FUNCTIONS
------
oracle
Oracle
-----
racle
----------
####oracle
----------
oracle^^^^
15
CONVERSION FUNCTIONS
4 rows updated.
SQL> select * from studs;
--------
017,145
RESULT
-----------
16-jul-2008
DATE FUNCTIONS
SYSDATE
---------
16-JUL-08
SYSDATE RESULT
--------- ---------
16
16-JUL-08 16-NOV-08
SYSDATE RESULT
--------- ---------
16-JUL-08 31-JUL-08
SYSDATE RESULT
--------- ---------
16-JUL-08 20-JUL-08
RESULT
---------
16.935484
GROUP BY CLAUSE
SAREA RESULT
-------------------- ------------
annanagar 1000
nungambakkam 500
kilpauk 100
HAVING CLAUSE
SQL> select sarea, sum(spocket) result from studs group by sarea having spocket<600;
SAREA RESULT
-------------------- ------------
nungambakkam 500
kilpauk 100
DELETION
17
Syntax:
1 row deleted.
Table created.
1 row created.
SQL>
PRODNAME PRODNO
------------------------------ ----------
table 10001
chair 10010
desk 10110
cot 11110
sofa 10010
tvstand 11010
SET OPERATIONS
SQL> select prodname from product where prodno=10010 union select prodname
from sale where prodno=10010;
PRODNAME
------------------
Chair
Sofa
SQL> select prodname from product where prodno=11110 intersect select prodname
from sale where prodno=11110;
PRODNAME
------------------
Cot
Result
Ex. No: 3
Nested Queries
Date: 10-03-2021
Aim
To write an SQL application that creates tables and perform certain operations based
on the concept of nested queries.
GIVEN APPLICATION
A department can control any number of projects but a project is controlled only by one
department. An employee can work in any number of projects on a day but an employee is
not permitted to work more than once on a project on the same day. Develop suitable
queries.
SQL> create table sempls( eno number(10) primary key, ename varchar2(10),
edob varchar2(15), gender varchar2(10), doj varchar2(15),desg varchar2(30),
bpay number(10), dno number(10));
Table created.
1 row created.
1 row created.
21
1 row created.
1 row created.
SQL> create table sdments( dno number(10), dname varchar2(30)); Table created.
DNO DNAME
--------- ------------------------------
1 cse
2 it
1 row created.
1 row created.
PNO PNAME DN
O
------- ------------------------------ ---------
--
81 aaa 1
82 bbb 1
83 ccc 1
84 ddd 2
85 Eee 2
SQL> create table sworks (eno number(10) , pno number(20) , date work
varchar2(20) , intime number(10),outtime number(10));
Table created.
1 82 11th july 10 11
1 83 11th july 11 12
1 84 11th july 12 1
1 85 11th july 1 2
2 85 12th july 8 9
QUERY 1
This querylists the details of employees who earn a basic pay that is less than the
average basic pay of the employees.
SQL> select * from sempls where bpay < (select avg(bpay) from sempls);
2 2
QUERY 3
This query lists the details of employees who earn a basic pay in the range 10000 to
20000. SQL> select * from sempls where bpay between 10000 and 20000;
4 july
3 mala 17th F 19th lec 19000 1
june june
4 nila 20th F 19th sr.le 20000 1
june june c
QUERY 4
This query lists the details of employees who have worked in projects controlled
by department name = cse.
QUERY 5
This query lists the employee number, employee name, department number, date worked if
the employee has worked in more than 4 projects on a day.
Result
Ex. No: 4
Join Operation
Date: 24-03-2021
Aim
Description
JOINS
INNER Join
This is a simple JOIN in which the result is based on matched data as per the equality condition
specified in the query.
Example:
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
29
ID NAME ID Address
1 abhi 1 DELHI
2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I
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.
Example:
ID NAME
1 abhi
2 adam
3 alex
4 anu
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
30
ID NAME Address
1 abhi DELHI
2 adam MUMBAI
3 alex CHENNAI
Outer JOIN
Outer Join is based on both matched and unmatched data. Outer Joins subdivide further into,
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.
Example:
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
32
ID Address
33
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abh 1 DELHI
i
2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I
4 anu nul null
l
5 ashish null null
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.
Example :
ID NAME
1 abhi
2 adam
3 alex
4 anu
5 ashish
35
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I
Nu null 7 NOIDA
ll
Nu null 8 PANIPA
ll T
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.
Example:
ID NAME
36
1 abhi
2 adam
3 alex
4 anu
5 ashish
ID Address
1 DELHI
2 MUMBAI
3 CHENNAI
7 NOIDA
8 PANIPAT
ID NAME ID Address
1 abhi 1 DELHI
2 ada 2 MUMBA
m I
3 alex 3 CHENNA
I
4 anu nul null
l
5 ashi nul null
sh l
Nu null 7 NOIDA
ll
Nu null 8 PANIPA
ll T
38
Result
Date :
31- 03-
2021
Aim:
To Implement Simple Views, Complex Views Synonyms, Sequence, Indexes and Save point.
Description:
View
Syntax:
1. Create a View that holds only the Branch name. Name the View as Branch_Name_View
Ans:
BRANCHNAME
------------------------------
Civil
Computer Science
Electrical
Electronics
Information Technology
40
Instrumentation
Mechanical
MBA
MCA
9 rows selected.
2. Create a View that holds Branch Number and Average Mark of Each Branch. Name the
view as Average_Mark_View.
Column Alias
Name
Avg(Mark) - Average
Mark
Branchno - Branch
Number
---------- ------------
1 71.5
2 92.6666667
3 90
4 75
5 100
6 85
7 82.5
7 rows selected.
Synonym
A synonym is an alternative name for objects such as tables, views, sequences, stored
procedures, and other database objects
Syntax
41
A synonym name E_MP is created for EMP table located in SCOTT schema. Now we can able
to access the EMP table from SYSTEM schema itself(I.E the schema in which you currently
logged in)
COUNT(*)
----------------
14
This DROP statement would drop the synonym called E_MP that we defined earlier.
SEQUENCE
Creation of sequence
42
Example:1
Maxvalue 100
Start with 1
Increment by 1
No cache
No cycle
Sequence created.
Example:2
MINVALUE 1
MAXVALUE 120
START WITH 1
INCREMENT BY 1
CACHE 20;
MAXVALUE 999999999999999999999999999
PSEUDO COLUMN:
Syntax:
Sequence_name.CURRVAL;
43
Sequence_name.NEXTVAL:
Example:
SQL>Select e_id_seq.NEXTVAL from dual;
NEXTVAL
-----------------
1
SQL>Select e_id_seq.CURRVAL from dual;
CURRVAL
-----------------
EMP table.
'30-MAY-2005',80,'[email protected]');
Drop Sequence
Once you have created your sequence in Oracle, you might find that you need to remove it
Syntax
44
For example:
INDEX
Creating an Index
Syntax
Confirming an Index
USER_INDEXES data dictionary view contains the name of the INDEX and its uniqueness.
Example:
ON student(registerno);
In this example, we've created an index on the student table called student_idx. It consists
of only one field - the registerno field.
We could also create an index with more than one field as in the example below:
ON student (registerno,name);
Drop an index
Syntax
EXAMPLE
Result
Thus the creation of Simple Views, Complex Views Synonyms, Sequence, Indexes and Save
point were successfully completed.
Ex. No :6
Implicit and Explicit Cursors
Date : 7-4-21
Aim :
Procedure:
The oracle engine uses a work area for its internal processing in order to execute an SQL
statement. This work area is private to SQL’s operations and is called a cursor. A cursor is a
mechanism by which you can assign a name to a "select statement" and manipulate the
information within that SQL statement.
Inplicit Cursors
Explicit Cursors
Implicit cursor attributes can be used to access information about status of last insert,
update, delete or single - row select statement. This can be done by preceding the implicit
cursor attribute with cursor name (i.e. sql)
Explicit cursor is defined in the declarative part of a pl/sql block. This is done by naming the
cursor and mapping it to a query.
The commands used to control the cursor are DECLARE, OPEN, FETCH and CLOSE.
A cursor is a SELECT statement that is defined within the declaration section of your
PLSQL code. We'll take a look at three different syntaxes for cursors.
1. Cursor without parameters (simplest)
CURSOR cursor_name
IS
SELECT_statement;
IS
SELECT_statement;
CURSOR cursor_name
RETURN field%ROWTYPE
IS
SELECT_statement;
Once you've declared your cursor, the next step is to open the cursor.
OPEN cursor_name;
The purpose of using a cursor, in most cases, is to retrieve the rows from your cursor so
that some type of operation can be performed on the data. After declaring and opening
your cursor, the next step is to FETCH the rows from your cursor.
The final step of working with cursors is to close the cursor once you have finished using it.
CLOSE cursor_name;
Result
Thus the implementation of Implicit and Explicit cursors were successfully completed.
49
Ex. No :7
Integrity Constraints
Date : 21-4-21
Aim
1 row created.
*
ERROR at line 1:
abcde 11
fghij 12
SQL> create table depts( dname varchar2(30) not null, did number(20) not null check
(did<10000));
50
Table created.
*ERROR at line 1:
51
DNAME DID
------------------------------ ---------
sales 9876
marketing 5432
SQL> create table airports (anamevarchar2(30) not null , aid number(20) not null, acity
ERROR at line 1:
ORA-02290: check constraint (ITA.SYS_C003187) violated
SQL> create table book (bnamevarchar2(30) not null, bid number(20) not
null unique); Table created.
*
ERROR at line 1:
BNAME BID
------------------------------ ---------
SQL> create table orders(oname varchar2(30) not null , oid number(20) not null
, unique(oname,oid))
; Table created.
1 row created.
1 row created.
*
ERROR at line 1:
54
ONAME OID
------------------------------ ---------
chair 2005
table 2006
chair 2007
SQL> create table custo( cname varchar2(30) not null , cid number(20) not
null primary key);
Table created.
55
1 row created.
ERROR at line 1:
ORA-00001: unique constraint (ITA.SYS_C003165) violated
------------------------------ ---------
jones 506
hayden 508
SQL> create table branches(bname varchar2(30) not null , bid number(20) not
null , primary key(bname,bid));
Table created.
*
56
ERROR at line 1:
BNAME BID
------------------------------ ---------
annanagar 1005
adyar 1006
annanagar 1007
57
ALTER TABLE
ENAME DN EDDRESS
O
-------------------- --------- --------------------
x 11 10 gandhi road
y 22 12 m.g. road
SQL> select city, ename from depts, s2emp where depts.dno = s2emp.dno;
CITY ENAME
-------------------- --------------------
chennai x
hyderabad y
Res
ult
Thus the constraints were implemented and the tables were created
various successfully.
59
Ex. No: 8
Aim
PL/SQL is a combination of SQL along with the procedural features of programming languages.
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL code can be stored
in the client system (client-side) or in the database (server-side).
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword DECLARE.
This section is optional and is used to declare any placeholders like variables, constants, records
and cursors, which are used to manipulate data in the execution section. Placeholders may be
any of Variables, Constants and Records, which stores data temporarily. Cursors are also
declared in this section.
60
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword BEGIN and
ends with END. This is a mandatory section and is the section where the program logic is written
to perform any task. The programmatic constructs like loops, conditional statement and SQL
statements form the part of execution section.
61
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword EXCEPTION.
This section is optional. Any errors in the program can be handled in this section, so that the
PL/SQL Blocks terminates gracefully. If the PL/SQL Block contains exceptions that cannot be
handled, the Block terminates abruptly with errors.
Every statement in the above three sections must end with a semicolon ; . PL/SQL blocks
can be nested within other PL/SQL blocks. Comments can be used to document code.
DECLARE
Variable declaration
BEGIN
Program Execution
EXCEPTION
Exception handling
END;
DECLARE
dbms_output.put_line(message);
END;
/
The end; line signals the end of the PL/SQL block. To run the code from SQL command line, we
need to type / at the beginning of the first blank line after the last line of the code. When the
above code is executed at SQL prompt, it produces following result:
62
Hello World
A constant holds a value that once declared, does not change in the program. A constant
declaration specifies its name, data type, and value, and allocates storage for it. The declaration
can also impose the NOT NULL constraint.
Declaring a Constant
A constant is declared using the CONSTANT keyword. It requires an initial value and does not
DECLARE
- constant
declaration pi
constant number :=
3.141592654; -- other
declarations radius number(5,2);
dia number(5,2);
circumference number(7,
2); area number (10, 2);
BEGIN
- processing
:= radius * 2;
-- output
dbms_output.put_line('Circumference: ' ||
circumference); dbms_output.put_line('Area: ' ||
area); END;
When the above code is executed at SQL prompt, it produces the following result:
Radius: 9.5
Circumference: 59.69
Area: 283.53
Pl/SQL procedure successfully completed.
Diameter: 19
PL/SQL – Conditions
IF-THEN Statement
It is the simplest form of IF control statement, frequently used in decision making and changing
the control flow of the program execution.
Syntax:
IF condition THEN
S;
END IF;
IF (a <= 20)
THEN c:= c+1;
END IF;
Flow Diagram:
64
IF-THEN-ELSE Statement
Syntax:
IF condition THEN
S1;
ELSE
S2;
END IF;
Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE statements, when
the test condition is TRUE, the statement S1 is executed and S2 is skipped; when the test
condition is FALSE, then S1 is bypassed and statement S2 is executed. For example,
IF color = red THEN
Flow Diagram:
65
IF-THEN-ELSIF Statement
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-THEN
statement can be followed by an optional ELSIF...ELSE statement. The ELSIF clause lets
Syntax:
IF(boolean_expression 1)THEN
ELSE
S4; -- executes when the none of the above condition is true
66
END IF;
67
PL/SQL – Loops
There may be a situation when you need to execute a block of code several number of times. In
general, statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages:
Basic loop structure encloses sequence of statements in between the LOOP and END
LOOPstatements. With each iteration, the sequence of statements is executed and then control
resumes at the top of the loop.
Syntax:
LOOP
Sequence of statements;
END LOOP;
Syntax:
sequence_of_statements
END LOOP;
A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax:
Nested Loops
PL/SQL allows using one loop inside another loop. Following section shows few examples to
illustrate the concept.
LOOP
Sequence of statements1
LOOP
Sequence of statements2
END LOOP;
END LOOP;
END LOOP;
END LOOP;
71
Result
Ex. No: 9
Aim
SQL> declare
2 a varchar2(20);
3 begin
4 a:='Hello';
5 dbms_output.put_line(a);
6 end;
7 /
Hello
3 begin
4 a:=&a;
5 dbms_output.put_line(a);
6 end;
7 /
SQL> declare
2 a number(7);
3 b number(7);
4 c number(7);
74
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
16 end if;
17 end;
18 /
6: a:=5; Enter
value for b: 7 old
7: b:=&b; new 7:
b:=7; Enter value
for c: 1 old 8:
c:=&c; new 8:
c:=1;
3 begin
4 loop
75
5 dbms_output.put_line (a);
6 a:=a+1;
8 end loop;
9 end;
10 /
1
2
3
4
5
PL/SQL procedure successfully completed.
76
SQL> declare
2 a number:=1;
3 begin
4 while(a<5)
5 loop
6 dbms_output.put_line (a);
7 a:=a+1;
8 end loop;
9 end;
10 /
1
2
3
2 a number:=1;
3 begin
4 for a in 1..5
5 loop
6 dbms_output.put_line (a);
7 end loop;
8 end;
9 /
1
2
77
3
4
5
SQL> create table saccount (accno number(5), name varchar2(20), bal number(10));
Table created.
1 row created.
1 row created.
2 kala 30000
SQL> declare
2 a_bal number(7);
3 a_no varchar2(20);
4 debit number(7):=2000;
5 minamt number(7):=500;
6 begin
7 a_no:=&a_no;
13 end;
14
15 /
1 mala 18000
2 kala 30000
Result
Thus the various programs in PL/SQL were implemented and their output was verified.
80
Ex. No : 10
Procedures and Functions
Date: 12 - 05- 21
Aim
To write PL/SQL programs that executes the concept of functions and procedures.
Definition
ARGUMENT: It is the name of the argument to the procedure. Paranthesis can be omitted if
no arguments are present.
IN: Specifies that a value for the argument must be specified when calling the procedure ie.
used to pass values to a sub-program. This is the default parameter.
OUT: Specifies that the procedure passes a value for this argument back to it’s calling
environment after execution ie. used to return values to a caller of the sub-program.
INOUT: Specifies that a value for the argument must be specified when calling the
procedure and that procedure passes a value for this argument back to it’s calling
environment after execution.
81
RETURN: It is the datatype of the function’s return value because every function must
return a value, this clause is required.
PROCEDURES – SYNTAX
constant
declaration; begin
PL/SQL subprogram
body; exception
exception PL/SQL
block; end;
82
FUNCTIONS – SYNTAX
{is,as}
variable declaration;
constant declaration;
begin
PL/SQL subprogram
body; exception
exception PL/SQL
block; end;
Table created.
6 raise null_price;
7 else
84
10 exception
11 when null_price then
12 dbms_output.put_line('price is null');
13 end;
14 /
Procedure created.
2 begin
3 select actualprice into price from ititems where itemid=a;
7 end if;
8 end;
9 /
Procedure created.
2 begin
3 select ordid into identity from ititems where itemid=a;
4 if identity<1000 then
5 b:=100;
6 end if;
7 end;
8 /
86
Procedure created.
SQL> declare
2 a number;
3 b number;
4 begin
5 zzz(101,b);
6 dbms_output.put_line('The value of b is '|| b);
7 end;
8 /
4 end;
5 /
Procedure created.
SQL> declare
2 a number:=7;
3 begin
4 itit(a);
5 dbms_output.put_line(‘The updated value is ‘||a);
6 end;
7 /
The updated value is 8
1 row created.
TNO TFARE
--------- ------------
1001 550
1002 600
88
3 begin
4 select tfare into trainfunction from ittrain where tno=trainnumber;
5 return(trainfunction);
6 end;
7 /
Function created.
SQL> declare
2 total number;
3 begin
4 total:=aaa (1001);
5 dbms_output.put_line('Train fare is Rs. '||total);
6 end;
7 /
2 fact number:=1;
3 b number;
4 begin
5 b:=a;
6 while b>0
7 loop
8 fact:=fact*b;
89
9 b:=b-1;
10 end loop;
11 return(fact);
12 end;
13 /
Function created.
SQL> declare
2 a number:=7;
3 f number(10);
4 begin
5 f:=itfact(a);
7 end;
8 /
Result
Ex. No. 11
Triggers
Date: 12-05-21
Aim
Theory
In a DBMS, a trigger is a SQL procedure that initiates an action (i.e., firesan action) when
an event (INSERT, DELETE or UPDATE) occurs. Since triggers are event-driven specialized
procedures, they are stored in and managed by the DBMS. A trigger cannot be called or
executed; the DBMS automatically fires the trigger as a result of a data modification to the
associated table.
Syntax
The CREATE TRIGGER command defines and names a trigger that will be stored in the database.
table
] [DECLARE
declarations ]
BEGIN
statements
END
Example:
93
BEGIN
Sample Output :
SQL> INSERT INTO Student VALUES('ADITYA KUMAR',11305104005,2,'A','24 -JUL-
2005',99,'[email protected]');
Exercise
Step 1: Create a table Studentauditlog with following Fields Field Name Data Type
Audit_date Date
Audit_user Varchar2(25)
Audit_desc VARCHAR2(50)
v_actionVARCHAR2(50);
BEGIN
94
IF INSERTING THEN
v_action := 'Updated
Student(s)'; ELSIF DELETING THEN
v_action := 'Deleted
Student(s)'; END IF;
1 row created.
2. Write a Before row-level trigger that displays a message Number 3' before every new
student belonging to Branch student table. Name the Trigger as Student_Branch3_trig.
'New Students are added to Branch Number 3 is inserted into the
FOR EACH
ROW BEGIN
95
IF :NEW.branchno = 3 THEN
END IF;
END;
In the trigger code block, several special variables are available for use.
NEW
NEW is a pseudo-record name that refers to the new table row for insert and update operations
in row-level triggers. This variable is not applicable in statement-level triggers and in delete
operations of row-level triggers.
Its usage is: :NEW.column where column is the name of a column in the table on which the
trigger is defined.
The initial content of :NEW.column is the value in the named column of the new row to be
inserted or of the new row that is to replace the old one when used in a before row-level
trigger. When used in an after row-level trigger, this value has already been stored in the table
since the action has already occurred on the affected row.
In the trigger code block, :NEW.column can be used like any other variable. If a value is assigned
to :NEW.column, in the code block of a before row-level trigger, the assigned value will be used
in the new inserted or updated row
3. Write a Row level Trigger that displays a message prior to Delete operation on the
Student table. Name the Trigger as Student_DeleteAlert_trig.
CREATE OR REPLACE TRIGGER
Student_DeleteAlert_trig BEFORE DELETE ON student
FOR EACH
ROW BEGIN
Result
Date: 24-5-21
Aim
The General Syntax for exception handling is as follows. Here you can list down as many as
exceptions you want to handle. The default exception will be handled using WHEN others THEN:
DECLARE
<declarations
section> BEGIN
<executable command(s)>
EXCEPTION
........
Example
Let us write some simple code to illustrate the concept. We will be using the employee205 table
DECLARE
98
pssn number(4);
pfname varchar2(15);
pbdate date;
BEGIN
EXCEPTION
When the above code is executed at SQL prompt, it produces the following result:
Execution 1:
Enter value for pssn: 999
Execution 2:
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any
internal
database error, but exceptions can be raised explicitly by the programmer by using the
command
DECLARE
exception_name
EXCEPTION; BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program. A
user-defined exception must be declared and then raised explicitly, using either a RAISE
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
DECLARE
my-exception EXCEPTION;
Example:
100
The following example illustrates the concept. This program asks for assn, when the user enters
an invalid ssn, the exception invalid_ssn is raised.
DECLARE
pssn number(4);
inputssn number(4);
pfname varchar2(15);
pbdate date;
invalid_ssn EXCEPTION;
BEGIN
PSSN:=&inputssn;
IF Pssn<= 0 THEN
RAISE invalid_ssn;
ELSE
dbms_output.put_line('No such
Employee!'); WHEN others THEN
dbms_output.put_line('Error!');
END;
When the above code is executed at SQL prompt, it produces the following result:
SQL> /
8: PSSN:=999;
Name: NANDA
101
SQL> /
SQL> /
Result
Thus the PL / SQL blocks that handle all types of exceptions were successfully completed.
102
Ex. No: 13
Library Information System
Date:24 -05-21
Aim
Provides Access with the information it requires to join the information in the
tables together as needed.
Helps support and ensure the accuracy and integrity of your information.
Determine the purpose of your database: This helps prepare you for the remaining steps.
2.1.2 Find and organize the information required: Gather all of the types of information you
might want to record in the database, such as product name and order number.
2.1.3 Divide the information into tables: Divide your information items into major entities or
subjects, such as Products or Orders. Each subject then becomes a table.
103
2.1.4 Turn information items into columns: Decide what information you want to store in
each table. Each item becomes a field, and is displayed as a column in the table. For example,
an Employees table might include fields such as Last Name and Hire Date.
2.1.5 Specify primary keys: Choose each table’s primary key. The primary key is a column that
is used to uniquely identify each row. An example might be Product ID or Order ID.
104
2.1.6 Set up the table relationships: Look at each table and decide how the data in one table
is related to the data in other tables. Add fields to tables or create new tables to clarify the
relationships, as necessary.
2.1.7 Refine your design: Analyze your design for errors. Create the tables and add a few
records of sample data. See if you can get the results you want from your tables. Make
adjustments to the design, as needed.
These are ten general principles for user interface design. They are called "heuristics"
because they are more in the nature of rules of thumb than specific usability guidelines.
105
The system should always keep users informed about what is going on, through appropriate
feedback within reasonable time.
The system should speak the users' language, with words, phrases and concepts familiar to the
user, rather than system-oriented terms. Follow real-world conventions, making information
appear in a natural and logical order.
Users often choose system functions by mistake and will need a clearly marked "emergency
exit" to leave the unwanted state without having to go through an extended dialogue. Support
undo and redo.
Users should not have to wonder whether different words, situations, or actions mean the
same thing. Follow platform conventions.
Even better than good error messages is a careful design which prevents a problem from
occurring in the first place. Either eliminate error-prone conditions or check for them and
present users with a confirmation option before they commit to the action.
Minimize the user's memory load by making objects, actions, and options visible. The user
should not have to remember information from one part of the dialogue to another.
Instructions for use of the system should be visible or easily retrievable whenever appropriate.
Accelerators -- unseen by the novice user -- may often speed up the interaction for the expert
user such that the system can cater to both inexperienced and experienced users. Allow users
to tailor frequent actions.
Dialogues should not contain information which is irrelevant or rarely needed. Every extra of
information in a dialogue competes with the relevant units of information and diminishes
relative visibility.
Error messages should be expressed in plain language (no codes), precisely indicate the
problem, and constructively suggest a solution.
Even though it is better if the system can be used without documentation, it may be necessary
to provide help and documentation. Any such information should be easy to search, focused on
the user's task, list concrete steps to be carried out, and not be too large unit their
Front End Tool
Visual Basic 6.0 is a robust, object-oriented, sophisticated and powerful development platform,
ideally suited for producing impressive Windows applications.
It is a powerful and complete Windows application development system that enables us to use built-in
functions and subroutines for dozens of different tasks.
It also provides capability to produce custom libraries and objects that can be loaded at runtime
or bound into the distributed application.
108
Every time you load a VB or VBA project, you will be greeted by roughly the layout shown in
Figure and these five GUI tools. First, the toolbox(1) contains all the GUIelements/controls
needed to create any VB form and the front end to all VB programs. For example, after the
pointer tool there is the image control, label, textbox, and frame and command button as the
first five of 20 standard controls which are used constantly in VB programs. Another advantage
of these basic controls is that they fill 60-90% of all our programming needs and are
automatically included in the VB runtime.
Second is form(2). Think of it as yours- you can size it, color it, give it a caption
("Database Test" in this case) and fill the form with GUI controls which help your program do
useful works. Putting controls on your form is as easy as clicking on the control (say the
command button) in the toolbox and then dragging and sizing it on your form (see the "Exit"
button on the form).
The third part of the Basic canvas is the menus and toolbars (3) which manage and
control all of VB/VBA.Most of us will be familiar with many of the menu and icons. File, Edit,
View, Run, Window, Help menus should be familiar to any Word Perfect, Excel, or Netscape
users. Likewise icons for File Open, File Save, Cut, Copy, Paste, Find, Run programs, Pause
Program, Halt Program can be seen along the toolbar. Along with built in wizards and custom
command centers in some controls, this is the heart of VB.
Fourth is the Project Explorer (4) which you use to access all the forms and coding files
in your VB program. The PE-Project Explorer is such a handy navigation device you will find
yourself using it all the time to switch among different forms and code.
Fifth and even more frequently used than the Project Explorer is the Properties sheet
(5). Note that the "Exit" command button is highlighted in the form and is also the control listed
in the Properties sheet. The Properties sheet is both the elegance and the swamp of VB. If you
want to change the property of any control like its color, shape, caption, or whatever - the
Property sheet is the place to go. But a command button has 32 properties - and some controls
have hundreds, hence the swamp.
109
You will find in developing in Visual Basic that you spend a large percentage of time
using the Project Explorer and Property sheet. It is worthwhile to get to know them well.
Project Explorer is your means of navigating around the various parts of VB; while Property
sheets allow you to set the very basic look and feel plus behavior of all your forms in Visual
Basic.
Form Design
Forms don’t usually get much attention from code-level developers. We add a form and off
we go, plugging in various controls and using them as containers for information. But setting up
forms’ properties is important for creating visually pleasant, consistent, and intuitive interfaces.
You should specify the proper border style of a form. Your options are:
None
Fixed Single
Sizable
Fixed Dialog
Fixed Tool Window
Sizable Tool Window
Using None is rarely a good idea, since such forms don’t have a title bar or the control menu
box, so users can’t close or resize them. The default form value is Sizable (allowing users to
resize the form), but this is a good choice only in cases where all the form elements are
designed to resize along with the form itself.
The Fixed Dialog style offers a border and doesn’t allow a form to be resized, but it lacks
Minimize and Maximize buttons in the top-right corner. To include those buttons, use the
Fixed Single style. Sizable Tool Window and Fixed Tool Window styles are generally used for
forms that need to float over and allow changes to be made to the main forms.
110
You should also address the form’s start position. The available start position styles are:
Manual
Windows Default
CenterScreen
CenterOwner
The default style is Manual, which means that the form will appear in the same location at both
runtime and design time. Windows Default puts a form in the upper-left corner on the screen.
CenterScreen places a form in the center of the user’s screen regardless of the screen
resolution. CenterOwner places a form in the center of the owner form. An owner is a form on
top of which the current form is to appear. When no owner is specified, the form shows up in
the center of the desktop.
Before simply dropping controls on a form, consider what kind of data the control will
oversee and how your users will interact with that data. The guidelines provided below will help
you choose the best controls for a particular type of data.
The first rule of form controls is that they should have consistent characteristics, such as
look, feel, and size. Users shouldn't need to learn specific visual cues and usage parameters for
each control.
Your text box controls should be the same height as the combo boxes. By default, the height
property of text boxes is different from that of the combo boxes. You should change the height
value of the text boxes to match that of the combo boxes (since the height property is read-only
in combo boxes). Obviously, this rule applies only to single-line text boxes.
You should use the proper controls for the data you need to display. If you're displaying
read-only data, you should not use a text box and modify its properties so that users can’t make
changes to its text. Instead, use a label. Text box controls should be used only for editable data.
111
When you need to display fewer than five options in a list and you want the user to choose
only one item, option buttons are your best choice. Many applications use combo boxes to
display such information, but from the user's standpoint, it’s much better to see all options at
once rather than having to scroll through the listings in a combo box.
Keep in mind that when you want your users to be able to select more than one item from a
small list of selections, using check boxes is a good idea. As with option buttons, check boxes let
users see all options available at the same time, but check boxes also allow the selection of
multiple items from the list.
When you need to display a larger number of items for users to choose from, it’s not
feasible to use option buttons or check boxes because of the amount of real estate they would
take up on the form. In such cases, you should display data either in combo boxes or list boxes
to save space. You can use multiple-selection list boxes to let users select more than one item at
a time; combo boxes allow only one item to be selected.
Developers sometimes use combo boxes and list boxes to display more than one column of
data; however, grid controls may be easier for users to understand (and easier for you to code).
When using labels next to corresponding controls, left-align the labels and follow label
captions with a colon for better readability. Also, align labels vertically to the corresponding
controls. Figure A provides an example of these label rules in action.
Figure A
112
Always set the BackStyle property of label controls to Transparent to make sure your
labels have the same BackColor as the parent form.
Whenever you need to prevent users from using a control temporarily, it’s preferable to
disable the control rather than hide it. Disabling a control prevents the user from clicking it, but
it doesn’t significantly alter the way the form looks. Hiding controls may take your users by
surprise or lead them to believe that something is wrong with an application. When selecting
controls, also consider newer VB options, such as Tab Control, Tree View, Progress Bar, and
Toolbar, to improve the form layout and design.
SCREENSHOTS:
Result
Ex. No: 14
Student Information System
Date: 26 - 5 - 21
Aim
Menu Design
Theory
To start adding menu items to your application, open an existing project or start a new
project, then click on Tools in the menu bar of the Visual Basic IDE and select Menu Editor. When
you click on the Menu Editor, the Menu Editor dialog will appear. In the Menu Editor dialog , key
in the first item File in the caption text box. You can use the ampersand ( & ) sign in front of F so
that F will be underlined when it appears in the menu, and F will become the hot key to initiate
the action under this item by pressing the Alt key and the letter F. After typing &File in the Caption
text box, move to the name textbox to enter the name for this menu item, you can type in
mnuFile here. Now, click the Next button and the menu item &File will move into the empty space
below, as shown in the following diagram:
117
You can then add in other menu items on the menu bar by following the same procedure,
as shown in the diagram below:
when you click Ok, the menu items will be shown on the menu bar of the form.
118
Now, you may proceed to add the sub menus. In the Menu Editor, click on the Insert button
between File and Exit and then click the right arrow key, and the dotted line will appear.
This
119
shows the second level of the menu, or the submenu. Now key in the caption and the name.
Repeat the same procedure to add other submenu items. Here, we are adding New, Open,
Save, Save As and Exit.
Now click the OK button and go back to your form. You can see the dropped
down submenus when you click on the item File, as shown.
120
Finally, you can enter the code by clicking on any of the submenu items.
121
Exercise
Add Menu as per Specification and sample given. In the intro form add following Menus
Personal
Personal Detail
Branch wise Detail
Mark
Mark Detail
Grade Detail
Exit
In the Personal Information form add Menu to navigate to the Main Menu(IntroForm)
In the Mark form add Menu to navigate to the Grade Details(Grade Form)
In the Grade form add Menu to navigate to the Mark Details(Mark Form)
Add Exit and Back as Required.
Coding
Sample Coding for Intro Form
End Sub
Private Sub GradeDetail_Click()
Unload Me
Load Grade
Grade.Show
End Sub
Mark.Show
End Sub
Load Student
Student.Show
End Sub
If Adodc1.Recordset.EOF Then
Adodc1.Recordset.MoveLast
End If
End Sub
If Adodc1.Recordset.BOF Then
Adodc1.Recordset.MoveFirst
End If
End Sub
Adodc1.Recordset.Update
End Sub
MsgBoxcs
End Sub
Load Intro
Intro.Show
End Sub
124
SCREENSHOTS:
Intro Form:
125
Registration Form
126
Result
Ex. No :15
Simple Calculator
Date : 26- 5- 21
Aim
Procedure:
Step1: create a new project in visual basic using the option file---> new project.
Step2: In the form use the front end tools in the toolbox like textbox, label, command button
and create a front end Design for the simple calculator.
Step3: Open the properties window for the toolsand select properties. Now the properties
Window is opened.
Step4: Set properties for each tool in the form like caption, name, etc.
Step5: Double click each and every tool to open the project code window.
Step7: write the code for the simple operations in the calculator like Addition, subtraction,
multiplication and division.
Step7: The code is Automatically compiled at the end of each line while pressing the Enter key.
Step7: now execute the code by click the F5 button in the keyboard or select Run--->start.
Step8: after successfully executing the project create the executable file by Select the option
file---> make file.exe.
128
SCREENSHOT:
CODING:
129
Dim a, b, c, d As Integer
display.Text = display.Text +
button0.Caption End Sub
display.Text = display.Text +
button1.Caption End Sub
display.Text = display.Text +
button2.Caption End Sub
130
display.Text = display.Text +
button3.Caption End Sub
display.Text = display.Text +
button4.Caption End Sub
display.Text = display.Text +
button5.Caption End Sub
display.Text = display.Text +
button6.Caption End Sub
display.Text = display.Text +
button7.Caption End Sub
display.Text = display.Text +
button8.Caption End Sub
display.Text = display.Text +
button9.Caption End Sub
a = Val(display.Text)
display.Text = ""
d=1
131
End Sub
a = Val(display.Text)
display.Text = ""
d=2
End Sub
a = Val(display.Text)
display.Text = ""
d=3
End Sub
132
a = Val(display.Text)
display.Text = ""
d=4
End Sub
b = Val(display.Text)
If d = 1 Then
c=a+b
display.Text = c
ElseIf d = 2
Then c = a - b
display.Text = c
ElseIf d = 3
Then c = a * b
display.Text = c
ElseIf d = 4
Then c = a / b
display.Text = c
End If
End Sub
Private Sub
clear_Click() a = 0
b=0
c=0
display.Text =
133
End End
Sub
display.Text = display.Text +
decimalpoint.Caption End Sub
134
OUTPUT:
135
Result