Professional Documents
Culture Documents
Contact me=9700064061
CONTENTS ____________________________________
Advantages……………………………………………………………………………………
Data Abstraction……………………………………………………………………………..
Data Models…………………………………………………………………………………..
DataBase Facilities………………………………………………………………………….
Structure of a DBMS……………………………………………………………………..…
PART-2 =====SQL.
What is SQL…………………………………………………………………………………..
SQL Statements……………………………………………………………………………..
(i)SQL*PLUS commands
(ii)PL/SQL commands
(iii)SQL commands
Built Functions………………………………………………………………………………
Set Operators………………………………………………………………………………
Views…………………………………………………………………………………………
Advantages
Sequence……………………………………………………………………………………
Index…………………………………………………………………………………………
Dynamic SQL………………………………………………………………………………
Embedded SQL……………………………………………………………………………
PART-3 =====PL/SQL.
Introduction to PL/SQL………………………………………………………………….
Advantages…………………………………………………………………………………
Block Structure……………………………………………………………………………
DataTypes of PL/SQL……………………………………………………………………
Architecture………………………………………………………………………………
Trigger……………………………………………………………………………………..
Advantages of trigger………………………………………………………………….
Cursor………………………………………………………………………………………
4. Create the BOOK table as in the 3rd program add one field as
(data_of_purchase), AND Status could be as same as in that table.
(A) Create a form to accept the data from the user with appropriate
validation checks.
(B) Generate queries to do the following:-
(i) List all those books which are new arrivals.The books which are
acquired during the last 6 months are categorized as new arrivals.
(ii) List all those books that cannot be issued and purchased 20 years
back (or) ago.
Introduction to DBMS
Advantages of DBMS:
DATA ABSTRACTION:
Physical Level:
Conceptual Level:
View Level:
They are used in describing data at the conceptual and view levels.
Some of the widely known models are
DATABASE FACILITIES:
STRUCTURE OF A DBMS:
Data Manager:
File Manager:
It is responsible for the structure of files and managing the file space and
also for locating the block containing required record, requesting this block
from the disk manager, and transmitting the required record to the data
manager.
Disk manager:
Query Processor:
The query processor is used to interpret the online user’s query and covert
it into an efficient series of operations in a form capable of being sent to the
data manager for execution. It uses data dictionary to find the structure of
the relevant portion of the database and uses this information in modifying
the query.
Data Files:
Data files contain data portion of the database.
Data Dictionary:
A data dictionary is a file that contains metadata. i.e. data about data. This
file is consulted before actual data is read or deleted in the database
system.
Different types of Keys:
Attribute: An object or an entity is characterized by its properties or
attributes, they can also be referred as field.
Ex: empno attribute in the employee table and deptno attribute in dept
table.
2. Foreign key: An attribute which is a primary key in its own table and
is used as a reference in another table is called foreign key.
3. Super Key: A primary key with a combination of other attributes for
unique identification is called super key. In other words primary key is
a minimum super key.
Ex: Empno along with ename is super key.
4. Candidate Key: The super key for which no proper subset is a super
key such a minimal super key is a candidate key.
Ex: Ename is a candidate key
What is SQL?
ANS:-
SQL (pronounced "ess-que-el") stands for Structured Query Language. SQL is used to
communicate with a database. According to ANSI (American National Standards Institute), it is
the standard language for relational database management systems. SQL statements are used to
perform tasks such as update data on a database, or retrieve data from a database. Some common
relational database management systems that use SQL are: Oracle, Sybase, Microsoft SQL
Server, Access, Ingres, etc. Although most database systems use SQL, most of them also have
their own additional proprietary extensions that are usually only used on their system. However,
the standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create", and "Drop"
can be used to accomplish almost everything that one needs to do with a database. This tutorial
will provide you with the instruction on the basics of each of these commands as well as allow
you to put them to practice using the SQL Interpreter.
(OR)
SQL is the official standard language used to access data held in the
databases.
SQL organizes data as tables , indexes , views etc. SQL is the
tool for organizing , managing and retrieving data stored in the
database.
SQL provides various features like portability , client-
server architecture ,dynamic data definition , multiple views of data etc.
(OR)
SQL (Structured Query Language) is a standard interactive and programming language for
getting information from and updating a database. Although SQL is both an ANSI and an ISO
standard, many database products support SQL with proprietary extensions to the standard
language. Queries take the form of a command language that lets you select, insert, update,
find out the location of data, and so forth. There is also a programming interface.
(OR)
(Structured Query Language) Pronounced "S-Q-L" or "see-quill," a language used to
interrogate and process data in a relational database. Originally developed by IBM for its
mainframes, all database systems designed for client/server environments support SQL. SQL
commands can be used to interactively work with a database or can be embedded within a
programming language to interface to a database. Programming extensions to SQL have turned
it into a full-blown database programming language, and all major database management
systems (DBMSs) support the language.
ANSI standardized SQL, but most database management systems (DBMSs) have some
proprietary enhancement, which if used, makes SQL non standard. Moving an application from
one SQL database to another may require tailoring to convert some command.
SQL Statements:
DML
Data Manipulation Language (DML) statements are used for managing data within schema objects. Some
examples:
DCL
Data Control Language (DCL) statements. Some examples:
DDL COMMANDS:
CREATE,ALTER,DROP AND TRUNCATE ARE CALLED DDL COMMANDS. They are called
Data Definition since they are used for defining the data. That is the structure of the
data is known through these DDL commands.
DML COMMANDS:
DML commands are used for data manipulation. Some of the DML commands
insert,select,update,delete etc. Even though select is not exactly a DML language
command oracle still recommends you to consider SELECT as an DML command.
TCL:
For revoking the transactions and to make the data commit to the database we use
TCL. Some of the TCL commands are:
1. ROLLBACK
2. COMMIT
DCL:
Data Control Language is used for the control of data. That is a user can access any
data based on the priveleges given to him. This is done through DATA CONTROL
LANGUAGE. Some of the DCL Commands are:
1. GRANT
2. REVOKE.
DML (Data Manipulation Language). These SQL statements are used to retrieve and
manipulate data. This category encompasses the most fundamental commands
including DELETE, INSERT, SELECT, and UPDATE. DML SQL statements have only minor
differences between SQL variations. DML SQL commands include the following:
DDL (Data Definition Language). These SQL statements define the structure of a
database, including rows, columns, tables, indexes, and database specifics such as
file locations. DDL SQL statements are more part of the DBMS and have large
differences between the SQL variations. DML SQL commands include the following:
DCL (Data Control Language). These SQL statements control the security and
permissions of the objects or parts of the database(s). DCL SQL statements are also
more part of the DBMS and have large differences between the SQL variations. DML
SQL commands include the following:
SQL*PLUS COMMANDS:=
SQL COMMANDS:=
DELETE
INSERT
SELECT
COMMIT
ROLLBACK
SAVEPOINT
1.Varchar2(size):
It is a variable length string with a max length of ‘size’ bytes.
2. Char (size):
It specifies a fixed length character string. Max size is 255
3. Number (n):
It specifies integer type of data with max of n digits.
4.Number(p,s):
It specifies floating number with p as total no of digits and specifies the
number of digits to the right of decimal points.
Syntax:
Column constraints :
1. Primary Key: It will not allow null and duplicate values corresponding
to that column.
2. Not Null : It will allow null values corresponding to that column
3. Unique: It will not allow duplicate values corresponding to that
column.
4. Check: It will impose the constraints based on the condition being
mentioned on the column.
5. Reference( foreign key): It will impose the constraints based on the
condition being mentioned on the column
6. Reference (foreign key): It will refer to other column values that are
acting as primary key in other table.
7. On delete cascade: It will delete the values in the column in one
table, corresponding values in other table will be deleted
automatically, and it will work only references only.
Example 1:
Example 2:
To create a table from taking the records from existing table. When
creating a table based on existing table then it is going to transfer only not
null constraint, other constraints will not be transferred.
Example 1:
SQL>Create table Emp
As select Empno, Ename, Salary from Employee;
Syntax:
Alter table<table_name>
Add column_name data_type <column_constraint>
[Modify column_name data_type <column_constraint>];
Add: is used when ever you want to add a new column to the table.
Example 1:
Syntax:
Drop table<table_name>;
Insert command: is used to add rows(or records) to the table. The number
and sequence should match that of columns in the table.If the number of
data values is less, then specify the column names into which data is being
entered. To insert null values, NULL can be used.
Syntax:
Insert into<table_name>values(datavalue_1,
………..,datavalue_n);
Insert into<table_name>(column_1,column_3)
Values(datavalue_1,datavalue_3);
Delete Command: is used to delete the records from the specified table.
Syntax:
Delete <table_name>
Where<condition>;
Example 1: Deleting the employee holding empno1001
Syntax:
Update <table_name>
Set <field_name> = <value> ,
.
Example4: Give an increment of 10% salary whose salary is less than Rs.
1000
SQL> update employee set sal = sal*1.1 where sal <1000;
The DML transactions will not be saved implicitly based on the following
reasons.
SQL> Rollback;
Example:
Syntax:
Select < field_name_1>, …….. , <field_name_n> from <table_name>
where <condition> ;
Logical Operators:
And
Or
Not
Example 1: To display the employee information who are working in deptno
10 and salary greater than 2000.
SQL>select * from emp
Where deptno=10 and sal>2000;
Example 2: To display the employee information who are working as
manager corresponding to deptno 20.
SQL>select * from emp
Where job=’manager’ and depno=20;
Example 3: To display the employee information who are working in
deptno 10,20.
SQL>select * from emp
Where deptno=10 or dept=20;
Special Operators:
Is null
In
Between
like
Example 1: To display the employee information who are not receiving any
commission.
Example 1: To display the employee details whose names are ending with
‘s’.
SQL>select * from emp
Where ename like’%s’;
Example 3: To display the employee details whose name has ‘a’ as second
character and ‘r’ as last character.
SQL>select * from emp
Where ename like’_a%r’;
Example 2:To display employee information for whose who are working as
managers and receiving salary other than the range 2000 to 3000.
SQL>select * from emp
Where job=’manager’ and sal not between 2000 and 3000;
Example 3:To display the employee details who are working in dept other
than 20,30.
SQL>select * from emp
Where deptno not in (20,30);
Example 4:To display the employee details who are working in deptno
10,20 for their names not ending with ‘s’.
SQL>select * from emp
Where deptno in(10,20) and ename not like ‘%s’;
o Number Functions
o Character Functions
Group Functions:
6.min(expr): Is used to find the minimum value for the mentioned numerical
attribute.
Example: find the employees who is paid the least salary.
SQL>select min(sal) from emp;
abs(n)
sqrt(n)
power(n)
mod(n)
1.abs(n): Is used to find the absolute value of n.dual is dummy table for
Temporary manipulation.
CHARACTER FUNCTIONS:
Length(str)
Concate(str1,str2)
Substr(str,pos,n)
Ascii(char)
Chr(n)
DATE FUNCTIONS:
SQL>select months_between(’29-oct-03’,’29-apr-03’)
from dual;
3. Last day(date): Returns the last day in the month specified by the date
mentioned.
Example 2: To display the deptno.s along with their total salary for
which total salary is greater than 10,000 corresponding to deptno 10,20.
SQL>select deptno,sum(sal) from emp
Where deptno in (10,20)
Group by deptno
Having sum(sal)>10000;
SET OPERATORS:
Union
Intersection
Minus
1. union: Is used to take distinct rows from more than one select
statement.By using union all the duplication is not removed.
2.intersect: Is used to take common rows from more than one select
statement.
Example 1: To dispalyb the job’s in deptno. 10 and 20.
SQL>select job from emp
Where deptno=10
Intersect
Select job from emp
Where deptno=20;
2. minus: Is used to select the rows from more than first select
statement which are not in the second statement.
Example 5:To display the manager no.alng with the no.of employee’s
working under him should be maximum no.of employees compared with
the other members.
Advantages of views:
Creation of view:
Replace: Replace option is used whenever you want to over write the
existing select statement with new select statement.
With check option: When ever you want to restrict the user to insert thr
records which are satisfying the where condition of the view then we use
with check option.
Altering the sequence: whenever you want to change any options relatedt
What is SQL?
SQL (pronounced “sequal”) stands for Structured Query Language. Withe SQL, you can view
data - called Data Definiton Language or DDL and manipulate data - called Data Manipulation
Languate or DML. All of the above are just a fancy way to say that with SQL, the user can both
view and alter records in the database. To help , here are a couple of queries:
DDL or View
DML or Manipulate
Find the record for employee ID 101 and change the first name to John
What is PL/SQL?
Here is a definition of PL/SQL from Lewis Cunningham (an Oracle database expert):
“If I wanted to create my own, very short, definition of PL/SQL it would be this: PL/SQL is the
Oracle native programming language that provides database-centric application development. It
can natively call static SQL and provides multiple methods of calling dynamic SQL.
DIFFER:
SQL is a data oriented language for selecting and manipulating sets of data. PL/SQL is a
procedural language to create applications. You don’t normally have a “SQL application”. You
normally have an application that uses SQL and a relational database on the back-end. PL/SQL
can be the application language just like Java or PHP can. SQL may be the source of data for
your screens, web pages and reports. PL/SQL might be the language you use to build, format and
display those screens, web pages and reports.
However, some programs must build and process a variety of SQL statements at run time. For
example, a general-purpose report writer must build different SELECT statements for the various
reports it generates. In this case, the full text of the statement is unknown until run time. Such
statements can, and probably will, change from execution to execution. So, they are called
dynamic SQL statements.
Dynamic SQL statements are stored in character strings built by your program at run time. Such
strings must contain the text of a valid SQL statement or PL/SQL block. They can also contain
placeholders for bind arguments. A placeholder is an undeclared identifier, so its name, to which
you must prefix a colon, does not matter. For example, PL/SQL makes no distinction between
the following strings:
'DELETE FROM emp WHERE sal > :my_sal AND comm < :my_comm'
'DELETE FROM emp WHERE sal > :s AND comm < :c'
(OR)
You want to execute a SQL data definition statement (such as CREATE), a data control
statement (such as GRANT), or a session control statement (such as ALTER SESSION). In
PL/SQL, such statements cannot be executed statically.
You want more flexibility. For example, you might want to defer your choice of schema
objects until run time. Or, you might want your program to build different search
conditions for the WHERE clause of a SELECT statement. A more complex program might
choose from various SQL operations, clauses, etc.
You use package DBMS_SQL to execute SQL statements dynamically, but you want better
performance, something easier to use, or functionality that DBMS_SQL lacks such as
support for objects and collections.
(OR)
OR
Dynamic SQL:
Static SQL
• Allowing access to the database using the
Problems
• “*” indicates that all columns from the table,
TableName, but the number of columns will
vary with the choice of table.
• Data types of the columns will vary between
tables
• But if we do not know the number and data
type, we can not use FETCH statement
Dynamic SQL can overcome these problems
and allow more general-purpose software to
be developed.
As the following example shows, you can fetch rows from the result set of a dynamic multi-row
query into a record:
DECLARE
TYPE EmpCurTyp IS REF CURSOR;
emp_cv EmpCurTyp;
emp_rec emp%ROWTYPE;
sql_stmt VARCHAR2(200);
my_job VARCHAR2(15) := 'CLERK';
BEGIN
sql_stmt := 'SELECT * FROM emp WHERE job = :j';
OPEN emp_cv FOR sql_stmt USING my_job;
LOOP
FETCH emp_cv INTO emp_rec;
EXIT WHEN emp_cv%NOTFOUND;
-- process record
END LOOP;
CLOSE emp_cv;
END;
The next example illustrates the use of objects and collections. Suppose you define object type
Person and VARRAY type Hobbies, as follows:
Embedded SQL
Embedded SQL statements
ISO standard specifies embedded support for Ada, C,
COBOL, Fortran, Pascal, PL/1.
PL/SQL Block
A PL/SQL block contains logically
related SQL and PL/SQL statements.
Three sections in a typical PL/SQL block:
declaration (optional): declare
identifiers (variables and constants).
execution (required): execute SQL and
PL/SQL statements.
exception (optional): perform error
handling.
In Oracle Tools:
When it contains the PL/SQL engine, an application development tool can process PL/SQL
blocks and subprograms. The tool passes the blocks to its local PL/SQL engine. The engine
executes all procedural statements at the application site and sends only SQL statements to
Oracle. Thus, most of the work is done at the application site, not at the server site.
Furthermore, if the block contains no SQL statements, the engine executes the entire block at the
application site. This is useful if your application can benefit from conditional and iterative
control.
Frequently, Oracle Forms applications use SQL statements merely to test the value of field
entries or to do simple computations. By using PL/SQL instead, you can avoid calls to the Oracle
server. Moreover, you can use PL/SQL functions to manipulate field entries.
Advantages of PL/SQL
A good way to get acquainted with PL/SQL is to look at a sample program. The program below
processes an order for a tennis racket. First, it declares a variable of type NUMBER to store the
quantity of tennis rackets on hand. Then, it retrieves the quantity on hand from a database table
named inventory. If the quantity is greater than zero, the program updates the table and inserts
a purchase record into another table named purchase_record. Otherwise, the program inserts an
out-of-stock record into the purchase_record table
With PL/SQL, you can use SQL statements to manipulate Oracle data and flow-of-control
statements to process the data. You can also declare constants and variables, define procedures
Block Structure
PL/SQL is a block-structured language. That is, the basic units (procedures, functions, and
anonymous blocks) that make up a PL/SQL program are logical blocks, which can contain any
number of nested sub-blocks. Typically, each logical block corresponds to a problem or
subproblem to be solved. Thus, PL/SQL supports the divide-and-conquer approach to problem
solving called stepwise refinement.
A block (or sub-block) lets you group logically related declarations and statements. That way,
you can place declarations close to where they are used. The declarations are local to the block
and cease to exist when the block completes.
The following FIGURE shows, a PL/SQL block has three parts: a declarative part, an executable
part, and an exception-handling part. (In PL/SQL, a warning or error condition is called an
exception.) Only the executable part is required.
The order of the parts is logical. First comes the declarative part, in which items can be declared.
Once declared, items can be manipulated in the executable part. Exceptions raised during
execution can be dealt with in the exception-handling part.
PL/SQL lets you declare constants and variables, then use them in SQL and procedural
statements anywhere an expression can be used. However, forward references are not allowed.
So, you must declare a constant or variable before referencing it in other statements, including
other declarative statements.
Variables can have any SQL datatype, such as CHAR, DATE, or NUMBER, or any PL/SQL datatype,
such as BOOLEAN or BINARY_INTEGER. For example, assume that you want to declare a variable
named part_no to hold 4-digit numbers and a variable named in_stock to hold the Boolean
value TRUE or FALSE. You declare these variables as follows:
part_no NUMBER(4);
in_stock BOOLEAN;
You can also declare nested tables, variable-size arrays (varrays for short), and records using the
TABLE, VARRAY, and RECORD composite datatypes.
You can assign values to a variable in three ways. The first way uses the assignment operator
(:=), a colon followed by an equal sign. You place the variable to the left of the operator and an
expression (which can include function calls) to the right. A few examples follow:
The second way to assign values to a variable is by selecting (or fetching) database values into it.
In the example below, you have Oracle compute a 10% bonus when you select the salary of an
employee. Now, you can use the variable bonus in another computation or insert its value into a
database table.
SELECT sal * 0.10 INTO bonus FROM emp WHERE empno = emp_id;
The third way to assign values to a variable is by passing it as an OUT or IN OUT parameter to a
subprogram. As the following example shows, an IN OUT parameter lets you pass initial values to
the subprogram being called and return updated values to the caller:
DECLARE
my_sal REAL(7,2);
PROCEDURE adjust_salary (emp_id INT, salary IN OUT REAL) IS ...
BEGIN
SELECT AVG(sal) INTO my_sal FROM emp;
adjust_salary(7788, my_sal); -- assigns a new value to my_sal
Declaring a constant is like declaring a variable except that you must add the keyword CONSTANT
and immediately assign a value to the constant. Thereafter, no more assignments to the constant
are allowed. In the following example, you declare a constant named credit_limit:
Syntax: Declare
: /*Declaring block*/
Begin
: /*Execution block*/
Exception
: /*Exception block*/
End;
SQL>ed area
Declare
PL/SQL Datatypes
Every constant, variable, and parameter has a datatype (or type), which specifies a storage
format, constraints, and valid range of values. PL/SQL provides a variety of predefined
datatypes. For instance, you can choose from integer, floating point, character, Boolean, date,
collection, reference, and LOB types. In addition, PL/SQL lets you define your own subtypes.
NUMBER
The syntax follows:
NUMBER[(precision,scale)]
To declare fixed-point numbers, for which you must specify scale, use the following form:
NUMBER(precision,scale)
NUMBER Subtypes
You can use the following NUMBER subtypes for compatibility with ANSI/ISO and IBM types or
when you want a more descriptive name:
DEC
DECIMAL
DOUBLE PRECISION
FLOAT
INTEGER
INT
NUMERIC
REAL
SMALLINT
PLS_INTEGER
You use the PLS_INTEGER datatype to store signed integers. Its magnitude range is -2**31 ..
2**31. PLS_INTEGER values require less storage than NUMBER values.
Character Types
CHAR Subtype
The CHAR subtype CHARACTER has the same range of values as its base type.
LONG and LONG RAW
You use the LONG datatype to store variable-length character strings. The LONG datatype is like
the VARCHAR2 datatype, except that the maximum size of a LONG value is 32760 bytes.
You use the LONG RAW datatype to store binary data or byte strings. LONG RAW data is like LONG
data, except that LONG RAW data is not interpreted by PL/SQL. The maximum size of a LONG RAW
value is 32760 bytes.
RAW
You use the RAW datatype to store binary data or byte strings. another.
The RAW datatype takes a required parameter that lets you specify a maximum size up to 32767
bytes. The syntax follows:
RAW(maximum_size)
Logical Rowids
Logical rowids provide the fastest access to particular rows..
VARCHAR2
The syntax follows:
VARCHAR2(maximum_size [CHAR | BYTE])
VARCHAR2 Subtypes
The VARCHAR2 subtypes below have the same range of values as their base type. For example,
VARCHAR is just another name for VARCHAR2.
STRING
VARCHAR
DSINTERVAL_UNCONSTRAINED .
The PL/SQL compilation and run-time system is an engine that compiles and executes PL/SQL blocks and
subprograms. The engine can be installed in an Oracle server or in an application development tool such
as Oracle Forms.
In either environment, the PL/SQL engine accepts as input any valid PL/SQL block or subprogram. Figure
shows the PL/SQL engine processing an anonymous block. The PL/SQL engine executes procedural
statements but sends SQL statements to the SQL engine in the Oracle database.
PL/SQL Engine
//****>
THE PL/SQL ENGINE(Processing)==//
Trigger:-
A trigger is an event-driven block of
PL/SQL code.
An event could be an insertion of a tuple
into a table, a deletion of an existing tuple
from a table, and an update of a table.
A trigger fires (executes, activates) when
an event occurs.
Triggers are useful for enforcing various
integrity constraints and business rules.
Advantages of Triggers:
SQL>ed t1
Create or replace trigger eins
Before insert on emp for each row
Begin
If:new.sal>5000 then
Raise_application_erroe(-20001,’salary above 5000’);
End if;
End;
/
SQL>@t1
SQL>ed t2
Create or replace trigger updel
Before update or delete on dept for each row
Begin
Declare
No number(4);
If updating or deleting then
Select count(*) no from emp
Where deptno=:new.deptno;
If (no>1) then
Raise_application_erroe(-20001,’Records existing
in emp table’);
End if;
End if;
End;
/
Triggers:
Trigger: procedure that starts automatically if
specified changes occur to the DBMS.
Three parts:
Triggers: Example
CREATE TRIGGER youngSailorUpdate
AFTER INSERT ON SAILORS
REFERENCING NEW TABLE NewSailors
FOR EACH STATEMENT
INSERT
INTO YoungSailors(sid, name, age, rating)
SELECT sid, name, age, rating
FROM NewSailors N
WHERE N.age <= 18.
(OR)
Triggers are stored procedures which are fired when data is modified in an underlying table.
They can evaluate data being added to a table for validation purposes, or can make changes
in that or other fields depending on the value of that data. You can use them even to
execute a separate stored procedure, or to roll back a data modification or an entire
transaction.
Triggers are created in the Enterprise Manager, or in the Query Analyzer through the object
browser. There are also templates for triggers in the Query Analyzer (Edit|Insert Trigger).
Triggers can be created with the following syntax:
There are two types of triggers: AFTER and INSTEAD OF. After triggers AFTER TRIGGERS
fire after the data is changed, either by insert, delete, or update. If the data is
inappropriate, as defined in the trigger, the modification can be rolled back to where it was
before the data was modified. After triggers AFTER TRIGGERS cannot be placed on views,
and cannot be used on more than one table. Also, the text, ntext, and image columns
cannot be referenced in an after trigger. AFTER TRIGGERS.
After triggers AFTER TRIGGERS can be nested to 32 levels deep, and can be called
recursively, again to 32 levels.
Instead of INSTEAD OF triggers make the validation before the modification. However,
Instead of INSTEAD OF triggers CAN can be used on views. They do not allow recursion, and
you can only have one Instead of INSTEAD OF trigger per table. And you cannot use an
Instead of INSTEAD OF trigger with a cascade.
Cursors
Oracle uses work areas to execute SQL statements and store processing information. A PL/SQL
construct called a cursor lets you name a work area and access its stored information. There are
two kinds of cursors: implicit and explicit. PL/SQL implicitly declares a cursor for all SQL data
manipulation statements, including queries that return only one row. For queries that return more
than one row, you can explicitly declare a cursor to process the rows individually. An example
follows:
DECLARE
CURSOR c1 IS
SELECT empno, ename, job FROM emp WHERE deptno = 20;
(OR)
Cursor in PL/SQL
Consider an SQL query returning
In most situations that require an explicit cursor, you can simplify coding by using a cursor FOR
loop instead of the OPEN, FETCH, and CLOSE statements. A cursor FOR loop implicitly declares its
loop index as a record that represents a row fetched from the database. Next, it opens a cursor,
repeatedly fetches rows of values from the result set into fields in the record, then closes the
cursor when all rows have been processed. In the following example, the cursor FOR loop
implicitly declares emp_rec as a record:
DECLARE
CURSOR c1 IS
SELECT ename, sal, hiredate, deptno FROM emp;
...
BEGIN
FOR emp_rec IN c1 LOOP
...
salary_total := salary_total + emp_rec.sal;
To reference individual fields in the record, you use dot notation, in which a dot (.) serves as the
component selector.
Cursor Variables
Like a cursor, a cursor variable points to the current row in the result set of a multi-row query.
But, unlike a cursor, a cursor variable can be opened for any type-compatible query. It is not tied
to a specific query. Cursor variables are true PL/SQL variables, to which you can assign new
values and which you can pass to subprograms stored in an Oracle database. This gives you more
flexibility and a convenient way to centralize data retrieval.
Typically, you open a cursor variable by passing it to a stored procedure that declares a cursor
variable as one of its formal parameters. The following procedure opens the cursor variable
generic_cv for the chosen query:
SQL>ed prime.sql
Declare
N number:=&n;
I number:=2;
R number(3):=0;
SQL>@ prime;
OUTPUT:
PROGRAM---
---(1)
PL/SQL CODE:-
CODE
declare
2 ano number(10);
3 cn varchar2(35);
4 ba number(10);
5 re number(10) :=1000;
6 dep number(10);
7 wit number(10);
8 msg varchar2(50);
9 d3 varchar2(50);
10 begin
11 ano :=&accountno;
12 select acc_no,cust_name,bal_amount into ano,cn,ba from sb_account where
acc_no=ano;
13 dep :=&enter_for_deposit;
14 update sb_account set bal_amount=dep where acc_no=ano;
Output;
PROGRAM---
---(2)
Table created.
Table created.
( A)
PROGRAM---
---(3)
Table created.
TRIGGER:-
AbdulQader(SQL)> create or replace trigger LIBtrigger before INSERT OR DELETE OR
UPDATE on LIBRARY for each row
declare
sta varchar2(25);
pub number(5);
begin
select published,status into pub,sta from library where published>1;
if pub>=20 then
sta :='cannot be issued';
insert into LIBRARY value('sta') WHERE PUBLISHED>=20;
PROGRAM---
---(4)
QUEREIS:-
(i)
(ii)
PROGRAM---
---(5)
QUEREIS:-
(i)
AbdulQader(SQL)>SELECT S_NAME,ROLL_NO,DATE_OF_BIRTH
FROM STUDENT WHERE DATE_OF_BIRTH<='31-DEC-1991';
(ii)
PROGRAM---
---(6)
QUEREIS:-
(i)
AbdulQader(SQL)>SELECT SUPP_CODE,SUPP_NAME FROM
SUPPLIER WHERE SUPP_CODE IN(SELECT ITEM_CODE FROM ITEM
WHERE ITEM_CODE IN(ITEM_CODE));
(ii)
AbdulQader(SQL)>select item_code,item_name from item where
item_code not in(select supp_code from supplier where
supp_code>100);
PROGRAM---
---(7)
QUEREIS:-
(i)
AbdulQader(SQL)>SELECT CUST_ID,CUST_CITY,BRANCH_NAME
FROM BRANCH WHERE CUST_CITY=BRANCH_NAME;
(ii)
AbdulQader(SQL)>select cust_id,cust_name,cust_city from customer
where cust_city not in(select branch_name from branch where
branch_id>100);
PROGRAM---
---(8)
QUERIES:
(i)
AbdulQader(SQL)>SELECT BOOK_NO,TITLE,DATE_OF_PURCHASE
FROM BOOK WHERE DATE_OF_PURCHASE<'27-SEP-2009';
(ii)
AbdulQader(SQL)> select member_id,name,
number_of_books_issued,max_limit from member where
number_of_books_issued>5;
PROGRAM---
---(9)
(a) All the data are same which we are previously seen(program-8).
(B)
declare
cursor prog IS select book_no,member_id,
date_of_issued,due_date from book_issued
where book_no>100;
book number(10);
mem number(10);
dateissued number(15);
duedate number(15);
begin
open prog;
DBMS_OUTPUT.PUT_LINE(' BOOK_NO MEMBER_ID DATE_OF_ISSUED
DUE_DATE ');
DBMS_OUTPUT.PUT_LINE('-------- ------------ --------------- ------------');
LOOP
FETCH PROG INTO book,mem,dateissued,duedate;
PROGRAM---
---(10)
(A)
(B)
(i)
AbdulQader(SQL)> SELECT
STUDENT11.S_NAME,STUDENT11.DISTRICT,STUDENT_RANK11.RAN
K FROM STUDENT11,STUDENT_RANK11
WHERE STUDENT11.ROLL_NO=STUDENT_RANK11.ROLL_NO AND
STUDENT_RANK11.RANK=505;
(ii)
select student11.roll_no, student11.s_name,
student11.category,student_rank11.rank from student11,
student_rank11 where student11.category='BC' and
student_rank11.rank=505 and
student11.roll_no=student_rank11.roll_no;
/
PROGRAM---
---(11)
(A )
WE ARE ALREADY CREATED TABLES and FORM OF BOTH IN THE PROGRAM
OF--5.
Let us create (b),
(B )
(i)
AbdulQader(SQL)> SELECT STUDENT17.ROLL_NO,
STUDENT17.NAME,STUDENT17.AGE,COURSE17.COURSE_ID,COURS
E17.C_NAME FROM STUDENT17,COURSE17 WHERE
COURSE17.C_NAME='MCA' AND STUDENT17.AGE BETWEEN '01-
JAN-1991' ANd '31-DEC-1992';
PROGRAM---
---(12)
PROGRAM---
---(13)
declare
cursor progfourt is select
item_code,item_name,qty_in_stock,reorder_level from item where
item_code>100;
a number(5);
b number(5);
c number(5);
d varchar2(15);
begin
open progfourt;
DBMS_OUTPUT.PUT_LINE('ITEM_CODE ITEM_NAME QTY_IN_STOCK
REORDER_LEVEL');
DBMS_OUTPUT.PUT_LINE('---------- --------------- -------------- -------------');
LOOP
FETCH PROGFOURT INTO a,d,c,b;
PROGRAM---
---(14)
(B)
declare
a number(10);
b varchar2(25);
c varchar2(25);
d varchar2(25);
begin
select supp_code,supp_name,address,status into a,b,c,d from supplier
where supp_code=111;
if a > 100
then
update supplier set status='IMPORTANT' where supp_code
in(111,222,333,444,555,666,777,888,999,1010);
PROGRAM---
---(15)
(A)
(B)
PL/SQL CODE:-
DECLARE
A NUMBER(5);
B NUMBER(10);
C VARCHAR2(25);
BEGIN
SELECT ROLL_NO,SUB_OPTED,STATUS INTO A,B,C FROM
STUDENT16 WHERE ROLL_NO=1;
IF B<=5
THEN
UPDATE STUDENT16 SET STATUS='NOT OFFERED' WHERE
SUB_OPTED<=5;
DBMS_OUTPUT.PUT_LINE('SUCCESSIVELY UPDATE TO STATUS');
DBMS_OUTPUT.PUT_LINE('NOT OFFERED WHERE SUB_OPTED
ATLEAST 5');
PROGRAM---
---(16)
(A) we are already created form in the last program number 15.
(B)
Pl/sql code:-
DECLARE
A NUMBER(5);
B varchar2(20);
C VARCHAR2(25);
BEGIN
SELECT sub_id,faculty_code,STATUS INTO A,B,C FROM subject
WHERE sub_id=1;
IF A>0 --B='NOT OFFERED'
THEN
UPDATE Subject SET STATUS='NOT OFFERED' WHERE
faculty_code='NOT OFFERED';
END IF;
DBMS_OUTPUT.PUT_LINE('SUCCESSIVELY UPDATE TO STATUS');
DBMS_OUTPUT.PUT_LINE('NOT OFFERED WHERE faculty member
set not offered');
END;
PROGRAM---
---(17)
(B)
(i)
(ii)
PROGRAM---
---(18)
(A)Already created.
(B)
(ii)
PROGRAM---
---(19)
(A)Already created.
(B)
(i)
(ii)
PROGRAM---
---(20)
(A)
(B)
(i)
AndulQader(SQL)>select studentrank8.rno,studentrank8.rank,
student8.state from studentrank8,student8 where
studentrank8.rno=student8.rno and studentrank8.rank>100 and
student8.state='tamilnadu';
(ii)
AndulQader(SQL)>select studentrank8.rno,studentrank8.rank,
student8.category,student8.state
from studentrank8,student8 where studentrank8.rank>100
and student8.category='bc' and student8.state='andhra pradesh';
(i) (ii)