Data definition language

Create table command
‡ It is used to define a new table ‡ Each column definition of a table has three parts: 1. A name 2. Data type 3. size

syntax
‡ Create table table_name(column1 datatype(size),column2 datatype(size), columnN datatype(size)); ‡ Example: ‡ Create table student(roll_no number(10), name varchar(20), city varchar (20));

How to display a table
‡ If we want to display the information about the columns defined in a table then we use following syntax: describe table-name; Example: describe student

output
Name Roll_no Name DOB City State Null? type Number(10) Varchar(20) date Varchar(20) Varchar(20)

Constraints in create table command
1. 2. 3. 4. 5. Primary key constraint Unique constraint Not-null constraint Foreign key constraint Check constraint

Primary key constraint
‡ Primary key is applied to column so that this column can be used to uniquely identify each row in a table ‡ A table have only one primary key ‡ Primary key has following features: 1. Primary key does not allow duplicate values 2. It does not allow null values

syntax
‡ Column_name datatype(size) Primary Key ‡ Example: create table student(Roll_no number(10) Primary Key , name varchar(20) , city varchar (20)) OR ‡ Create table student(Roll_No number(10) , Name varchar(20) , City varchar(20) , Primary Key (Roll_No)); OR ‡ Create table student(Roll_NO number(10) , Name varchar(20) city varchar(20) , Constraint PK Primary Key(roll_no));

‡ Unique constraint will not allow the duplicate values in the column to which they are attached .Unique constraint ‡ The unique constraint is used for the candidate key columns so that they contain the unique values for different entities.

Characteristics of unique key ‡ No allow duplicate values ‡ Can accept null values ‡ A table can have more than one unique key .

. student_ID char(10) Unique .syntax ‡ Column_name datatype(size) Unique ‡ Example create table student( reg_no char(10) Primary Key . roll_no number(10) Unique . city varchar(20)).

Not null constraint ‡ It ensures that the table column will not left empty Syntax: column name datatype(size) Not Null .

Foreign key constraint The table in which foreign key is defined is called foreign table or detail table and the table whose primary key is referenced by the foreign table is known as Master table .

characteristics ‡ It contain only those values that are present in the primary key of master tabel ‡ Value in the foreign key can be null or duplicate values ‡ In foreign key if we insert a value which is not present in the primary key the oracle engine will reject the data ‡ A record in a master table cannot be deleted if the corresponding record in the foreign table exist .

Dept_id varchar (20) Refrences department(dept_id)).syntax column-name datatype(size) References Master-Table-name(column-name) Example: create table department( department_id char(10) Primary Key . after creating the master table foreign table is created as: Create table course (course_id char(10) Primary Key. . department_name varchar(10)).

Check constraint ‡ Used to specify the data validation for a column ‡ Check constraint is a Boolean expression that is evaluated to either True or False ‡ Before inserting a value into the column (to which check constraint is attached ) oracle engine evaluates the Boolean condition ‡ If the condition evaluated is true then database accepts the value othervise it do not accept the value .

age number (10) check (age BETWEEN 22 and 30)).syntax column-name datatype(size) Check (Boolean Expression) Example : suppose that in employee table the age of employee must be between 22 and 30 syntax: create table Employee(emp_id char(10) Primary key . . ename varchar (20).

Alter table command ‡ It is used to modify the structure of table which is already existing .

. .column-nameN datatype(size).Adding new column to an existing table syntax: Alter table table-name ADD(col-name1 datatype(size). column-name2 datatype(size).

Example: Alter table Employee Modify(emp_id varchar(20)). .Modifying an existing table ‡ Used to increase or decrease the column width and to change the datatype syntax: Alter table table-name MODIFY (column-name New-datatype(New Size)).

To add primary key Alter table table-name ADD Primary Key (column-name). .

Dropping the constraints ‡ To remove primary : Alter table table-name DROP constraint-name .

Dropping column from table ‡ Alter table table-name DROP column column-name. .

Drop table command ‡ DROP table table-name .

Rename command ‡ Use to change the name of existing table Syntax: Rename table-name TO New-table-name. .

Data manipulation language ‡ Used to access or manipulate the data values in the tables .

Insert command ‡ Used to insert data rows in a table ‡ We can either insert a row at a time or by inserting the data rows from already existing table .

. The number of values that appear in the parenthesis after the keyword values must match the number of columns in the list ..valueN).. colnameN)values(value1.syntax Insert into table-name (col-name1..

pune . mech . raj . column name is optional . dept_name . state) values ( E1 . MH ). city . 26 .example ‡ Insert into Emp( emp_id . age . name .

. .For inserting data rows from another table ‡ Insert into table-name1 select col-name1. col-nameN From table-name2 WHERE condition.

UPDATE COMMAND ‡ Use to modify already existing data values ‡ It is use to update either 1. A selected set of rows from a table SYNTAX: Update table-name SET col-name1 = value1.. All the rows from a table 2. . col-nameN= valueN .

.example ‡ Change the city of each employee to Chandigarh Update Emp SET City = Chandigarh .

Example: Update Emp SET Age = 34 Where ename = sunil . .Syntax for updating selected rows ‡ Update table-name SET Col-name1 = value1.. . col-nameN = valueN WHERE condition.

. A selected rows from a table Syntax for deleting all the rows Delete from table-name.DELETE COMMAND ‡ It is used to delete 1. All the rows from a table 2. for deleting specific rows Delete from Table-name Where codition.

.Rn .C2 From R1. Where P...R2. .. Cn .select ‡ Use to view or retrieve the rows from one or more tables Syntax: Select C1.

Use of select command ‡ ‡ ‡ ‡ To access all the rows and all the columns To access specific row and all the columns To access specific columns and all the rows To access specific row and specific column .

.To access all the rows and all the columns Select * from table_name.

To access specific columns select column-list from table_name. .

.To access specific rows select * from table_name When condition.

To access specific rows and specific columns select column-list from table_name where condition .

name. .Select command with distinct clause select DISTINCT column-name From table.

Select command with order by clause select * from table-name Order By column-name Sort-order. .

Select command with arithmetic operator select column_name arithmetic operation from table-name .

. alias-name from table name.Alias with select command ‡ Alias is used to rename the column while displaying the data . But the actual column name in the structure does not change SYNTAX: select column-name.

Select command with between operator select * from table-name Where column-name BETWEEN LL AND UL. .

Select command with like operator
‡ To match the string patterns ‡ LIKE operator use two wild card character 1. Percent(%) to match any string of any length 2. Underscore(_) to match a single character

example
1. St% matches with any string starting with St 2. %y matches with any string ends with y 3. Mo_ _ _ matches with any string started with Mo and has three letters after it 4. _ _ _ _ _a matches with any string ending with a and has 5 letters before 5. _ _ _ _ matches any four characters 6. _ _% matches any string which is atleast two characters

Cont

..

select * from table_name Where column-name LIKE R% ;

Select stmt with SET operation
‡ Union Syntax: Select-statement1 UNION Select-statement2;

intersect Select statement 1 INTERSECT Select.statement 2 .

Select command with dual table ‡ It is a small work-table ‡ It consist of only one row and one column ‡ The column name is Dand the value in this column is x .

example ‡ Query 1: Desc dual. Query 2: select * from dual. output: D x .

output: 4+4 8 to view today's date select Sysdate from dual. .Example ‡ Select 4+4 from dual.

Select command with aggregate functions ‡ Aggregate functions are the Oracle functions that takes collection of values as an input and produce a single value as an output 1. Min 3. Max 4. Count . Avg 2. Sum 5.

Avg ‡ It calculates the average value of specified column Select AVG(column-name) from table-name. .

count ‡ Counts the number of rows in a table 1. counts the number of rows in a table that have a non null value for specified column . count(*) . Count(column-name) . counts number of rows in table including duplicate and null values 2.

.C2. Cn Aggregate-function(column-name) From table-name Where condition Group By C1.Select command with Group By clause ‡ This clause creates a data set that contain several sets of record grouped together based on a condition Syntax: select C1.C2. Cn.

STUDENT RollNo 1 Name abc Branch cse city BOMBAY 2 def ME NOIDA 3 ghi cse BOMBAY 4 xyz ME BOMBAY .

of students From student Group By branch. . count(rollno) no.Example ‡ If we want to see that how many students are there in each branch Select branch.

condition with having class is evaluated after the groups are formed by group by clause .SELECT COMMAND WITH HAVING CLAUSE ‡ It is used to specify a condition on the Group by clause ‡ Having clause is equivalent to where cluase except that it acts on the record set but not on the individual record ‡ The main difference between where and having clauses is that . the condition with where clause is evaluated first and then it forms a group of rows which satisfy the condition whereas.

To show how many students are in CSE branch ‡ Select branch. . of Students From student Group By branch Having branch = CSE . count(rollno) No.

‡ Nested query can be formed using: 1. A query written inside another query is called sub-query. In connective 2. Non in connective 3. Non exists . Exists 4.Nested queries ‡ A query is a statement requesting the data from database .

Data control language ‡ It includes the commands that are related to the security of database ‡ Database administrator grants and revokes the user privileges ‡ A user can be granted all the privileges or some specific privilege ‡ On an object user can perform only those operations for which the privileges are granted to him .

Various object privileges ‡ ‡ ‡ ‡ ‡ ‡ ‡ ALTER: DELETE INSERT SELECT UPDATE INDEX With grant option .

.DCL commands syntax: Grant privileges ON object-name TO user-name WITH GRANT OPTION.

. select On Employee To RAJ.example ‡ To provide insert and select privilege ‡ ‡ ‡ ‡ SYNTAX: Grant insert.

To grant all the privileges ‡ SYNTAX: ‡ Grant All ‡ On Employee ‡ To SUNIL .

Revoke ‡ ‡ ‡ ‡ SYNTAX: Revoke privileges On object-name From user-name. .

Join ‡ When two tables get joined with the help of a column that have same data type and size in both the tables that relation is known as join ‡ With the use of Join we can access the data from multiple tables using single SQL statement .

column for table1 and table2 must have same data type as well as size . The above statement selects the rows of two tables .column. table2 Where table1. table2.SYNTAX select table1.column from table1 .column .column = table2.

Outer join ± Left outer join ± Right outer join 4. Cross join 2. Inner join or equi join 3. Self join .Types of join 1.

Cross join ‡ It is also called as Cartesian product of two tables ‡ Cross join of two tables results in a new table which contain each and every possible combination of rows of both the tables ‡ The resultant table may contain duplicate columns ‡ Thus cross join is usually not preferred .

table2.column .syntax select table1.column from table1 . Cross join does not include the where clause in its syntax The above syntax is used when column name in both the tables are same . table2.

table2. .When the column name is different SYNTAX: select column1 . column2 from table1.

Inner join ‡ ‡ ‡ ‡ It is also called EQUI join It is an improvement over cross join It include where clause in the select statement This is called equi join because condition under where clause uses the equality operator (=) to compare two values of table .

.syntax select table1.column.column. table2.column = table2. table2 where table1.column from table1.

‡ Equi join first perform the cross join on two tables and then shows only those rows which satisfies the condition under where clause ‡ If the where condition includes any operator except = then it is called as non-equality join ..Cont.

Outer join ‡ The outer join is denoted by + operator ‡ The + operator add the missing rows from first table to the resultant table of inner join ‡ For that row the values for corresponding columns of second table may be null .

Right outer join Which includes all the rows from second table Example: X(+) = Y .Types of outer join 1. Left outer join Which includes all rows from first table Example: X = Y (+) 2.

Self join ‡ It is used to join the table itself ‡ It performs the join operation on two copies of same table .

VIEW ‡ It is an oracle object that is used to implement the security ‡ A view is an imaginary table that is created from some other base table ‡ Through view a user may be allow to access specific column instead of accessing all the tables of database ‡ Purpose of view is to provide security to the data by restricting the access to the base table .

.Cont. ‡ Several views can be created from one base table ‡ A user working on a view is able to access only those columns of base table that are included in that view ‡ View act like a window to the base table from which it is created .

Read only view 2. Updatable view .Types of views 1.

Read only view ‡ This view is used only to view the data ‡ We are not allowed to do any changes in it .

update . delete . and other operations .Updatable view ‡ In which we can perform insert .

.Syntax for creating view create view view-name AS select column list From table-name Where condition.

department Dept_id 1 2 3 4 name CSE IT ECE ME .

HOD Dept_id 1 2 3 HOD_Name A B C .

Example of cross join ‡ Select Name . HOD. . HOD_name From Department .

output Name CSE IT ECE ME CSE IT ECE ME CSE IT ECE ME HOD_Name A A A A B B B B C C C C .

HOD_Name From department .det_id.EXAMPLE OF INNER JOIN ‡ Show the name of departments and their respective HOD s Select Name . .dept_id = HOD. HOD Where department.

output Name CSE IT ECE HOD_Name A B C .

HOD_Name From Department .dept_id(+).dept_id = HOD.Example of outer join ‡ Show the names of department and their respective HOD s . Also show the department name even if no HOD is appointed for that department Select Name . . HOD Where Department.

output Name CSE IT ECE ME HOD_Name A B C .

Example of self join ID 1 2 3 4 NAME W X Y Z HOD 2 4 .

name teacher .name HOD From teacher a .‡ Show the names of HODs with their teachers Select a. The above query creates two copies of table teacher . The alias for first copy is a and alias for second copy is c .id. c.hod = c. teacher c Where a.

output teacher M O HOD N P .

PL/SQL ‡ PL/SQL is a block structured query language which combines the features of SQL with procedural capabilities .

2. SQL cannot be used for programming because SQL does not provide the programming techniques of condition checking . SQL statements are passed to oracle engine one at a time which increases the traffic on the network which results in decrease of speed of data processing .Disadvantages of SQL 1. looping and branching etc.

On the occurrence of an error . the oracle engine displays its own error message . SQL does not allow the programmer to handle the errors To overcome above disadvantages of SQL .Cont 3. PL/SQL came into existance .

PL/SQL sends entire block of sql statements to oracle engine in one go . PL/SQL has SQL features as well as procedural capabilities 2.Advantages of PL/SQL 1.thus reduces the network traffic and results in icrease of processing speed 3. It allows the programmer to display user friendly error-message .

Cont
‡ PL/SQL programs are portable i.e. , these can run on any computer hardware and operating system where oracle is installed

Structure of PL/SQL Code BLOCK
‡ A PL/SQL code block is divided into four sections : 1. Declare section 2. Begin section 3. Exception section 4. End section

structure
DECLARE variable and constant declarations BEGIN SQL and PL statements EXCEPTION Error handling statements END;

DECLARE section
‡ Every code block starts with a declare section ‡ It is used to declare and initialize variables ‡ This section is optional

BEGIN ‡ It is an executable section which contain the SQL and PL/SQL executable statements ‡ It is compulsory section ‡ This section includes all the data manipulations. data retrieval . branching and looping construct .

Exception ‡ It contains the user defined error handler ‡ This section is executed only when an error occures .

End section This section indicates the end of a code block .

Variables and consonants 5. Character set 2. Data types 6. comments . Literals 4.Fundamentals of PL/SQL ‡ Fundamentals of PL/SQL includes: 1. Operators 3. Declarations 7. Assignment 8.

A Z and a z Numerals.* / <> = ! ~ ^ . () + . @ % Tabs and spaces .9 Symbols.Character Set ‡ ‡ ‡ ‡ ‡ PL/SQL character set include: Upper and lower-case letter . 0 . : .

Arithmetic operators 2. Logical operators 3. Literals: numeric literals character string boolean . Comparison operators 4.operators ‡ Operators can be classified into three groups 1.

Variables and constants ‡ Variable in PL/SQL is a named variable used to hold some data values ‡ Variable must start with a character and can be followed by maximum of 29 other characters ‡ Reserved words cannot be used as a variable name ‡ Constant declaration is similar to variable declaration except that keyword constant is added to variable name and a value is assigned immediately ‡ Ones a constant is de3clared no other assignment to the constants is possible .

BOOLEAN: used to store true false or null . DATE: used to store date and time data 5. Number: used to store numeric data 2. VARCHAR2: used to store variable length character data 4. CHAR: used to store alphanumeric data 3.Data types 1.

EXAMPLE: Age Number(5). DOB Date.declarations ‡ Before a variable can be used in the begin section .2). A number(10. Name Varchar2(20). it must be declared in the DECLARE section SYNTAX: variable-name datatype(size). .

. EXAMPLE: Pi constant number(4.Declaring constants SYNTAX: variable-name constant datatype(size) := value.2) := 3.14.

Assignment operator(:=) to get values from the user 2.assignments ‡ For manipulating data in the begin section . variables must be assigned some value ‡ Variable can be assigned in two ways 1. SELECT INTO clause to get values from database object .

USING SELECT INTO CLAUSE Select salary into sal from employee where empid = 12. ‡ B := c+d. .Example using assignment operator ‡ A := 10.

comments ‡ Single line: begins with double hyphen(--) ‡ Multiline: begins with a (/*) and ends with (*/) .

How to read value during runtime ‡ The symbol & is used to assign the value to the variable during runtime FOR EXAMPLE consider the num variable . to read the value for this variable during runtime following statement can be used: Num := &num. .

. ‡ When the program will execute the system will ask to enter the value and user can enter any value Enter the value of Num: 10 the value 10 is substituted at the place of &Num Num := 10..Cont.

SYNTAX: SQL> SET SERVEROUTPUT ON. the SERVEROUTPUT should be set ON.PUT_LINE ( hello ). .Displaying user message on the screen ‡ To display the message . Now we can display any message using DBMS_OUTPUT.

put_line( hello ). .Basic PL/SQL programs ‡ Write a PL/SQL code block to display the message . END. Declare Begin dbms_output. hello .

Begin a:=5.put_line( sum= ||c). b number(2). c number(2). . b:= 4. Dbms_output. END.To add two numbers Declare a number(2). C:= a+b.

Control statements ‡ Conditional control ‡ Iterative control ‡ Sequence control .

Conditional control ‡ IF-THEN ‡ IF-THEN-ELSE ‡ IF-THEN-ELSEIF .

IF THEN ‡ IF condition then sequence of statement. END IF. .

END IF. . ELSE statements2.IF THEN ELSE ‡ If condition then statements1.

If-then-elseif IF condition1 THEN statements1. ELSE Statement3. END IF. . ELSIF condition2 THEN statement2.

Iterative control ‡ LOOP ‡ WHILE-LOOP ‡ FOR-LOOP .

loop ‡ The keyword LOOP is placed before the first statement in the sequence and the keyword END LOOP after the last statement in the sequence ‡ To exit from the loop EXIT-WHEN statement can be used .

syntax LOOP sequence of statements. EXIT WHEN condition. then the loop will terminate unconditionally . The loop will complete when the condition under EXIT-WHEN clause is true If the condition is omitted from the above syntax. END LOOP.

put_line(i). END LOOP. EXIT WHEN i>=10. Begin i:= 1.EXAMPLE ‡ Write a program to display number from 1to 10 Declare i number (2). i:=i+1. . END. LOOP dbms_output.

While loop Syntax: WHILE condition LOOP sequence-of-statements. . END LOOP.

Cont ‡ Before executing the sequence of statements . the condition is evaluated. then the body of loop is executed and the control goes to the top of the loop. ‡ If it results in TRUE . the body will no get executed and the control goes to the statement immediate below the loop. . ‡ Thus the body of loop is executed each time the condition is TRUE. ‡ When the condition becomes FALSE.

a:=a+1. WHILE a<=10 LOOP dbms_output. END LOOP.example ‡ Write a program to print square of numbers from 1 to 10. Declare a number(2). . Begin a:=1. END.put_line(a*a).

once for each integer in the range ‡ Unlike WHILE-LOOP. the number of iterations through a FOR loop is known before the loop is entered .For loop ‡ The FOR-LOOP statement is used to specify a range of integers and then executes a sequence of statements.

. higher-bound LOOP sequence-of-statements.syntax FOR counter IN [REVERSE] Lower bound. . END LOOP.

. ‡ The lower and upper bounds are the integer values separated by double dot(. ‡ As long as the value of variable counter lies between the specified ranges. the sequence of statements keep on executing. ‡ The FOR loop initialize and increment the counter automatically ‡ Keyword REVERSE is optional .Cont..) and specify a range.

2.of-statements. ‡ If the reverse option is not used then. . counter is assigned values 1.5.Cont. the variable counter is assigned values ranging from lower bound to upper bound ‡ EXAMPLE: FOR counter IN 1.3..4.5 LOOP sequence.. Here. END LOOP.

1..Cont..3.2. ‡ If REVERSE option is used then. Here counter is assigned values 5.4. counter is assigned values ranging from upper bound to lower bound ‡ EXAMPLE: FOR counter IN REVERSE 1. END LOOP.5 LOOP sequence of statements. .

. i number(2). BEGIN FOR i IN 1.put_line( 2*||i|| = ||tatal). END.10 LOOP total:=2*I. dbms_output.EXAMPLE ‡ Write a PL/SQL block to display the table of 2 DECLARE Total number(4). END LOOP..

‡ The label is marked using tags <<labelname>>. ‡ Labelname is a user defiened name and it can appear either above or below the GOTO statement.Sequence control ‡ GOTO statement transfer the flow of control to a specified label unconditionally. .

.SYNTAX GOTO label-name.

<<O2>> dbms_output.Example ‡ Write a program to find the larger of two numbers using GOTO statement. GOTO O3.put_line( SUCCESSFULLY ). IF num1>num2 THEN GOTO O1. <<o3>> dbms_output. BEGIN num1:=&num1. DECLARE num1 number(2). <<O1>> dbms_output. END IF.put_line( greater is num1 = ||num1). END. num2:=&num2. num2 number(2). ELSE GOTO O2.put_line( greater is num2 = ||num2). .

‡ An event on a table can be INSERT. DELETE.DATABASE TRIGGERS ‡ It is the stored procedure that is automatically executed in response to certain events on a particular table or view in a database. or UPDATE statement on the table .

Enhance changes 5. Prevent changes 2. Audit changes 4. Log changes 3.NEED and USES of triggers ‡ Triggers are commonly used to : 1. Replicate data 6. Enhance performance .

Trigger action . Trigger restriction 3. Triggering event or statement 2.Parts of a trigger ‡ Three parts of trigger 1.

UPDATE event(when a record is being changed in a table). 2. INSERT event(when a new record is being inserted into table). DELETE event(when a record is being deleted from a table) . . 3.Triggering event or statement ‡ It is an SQL statement that makes a trigger to fire ‡ There are typically three triggering events that causes trigger to fire: 1.

only the trigger will fire ‡ But if Trigger restriction evaluated to be false.Trigger restriction ‡ It is a Boolean expression that must be true for a trigger to fire ‡ When an event occurs and Trigger restriction is evaluated to true then. the Trigger will not fire ‡ A Trigger restriction is specified using WHEN clause .

TRIGGER ACTION ‡ It is a PL/SQL code which is executed when an event occurs and trigger restriction is evaluated to TRUE .

Types of triggers 1. ROW triggers: A ROW trigger is fired for each row affected by a triggering statement .

regardless of the no. of rows affected by triggering statement .Statement trigger ‡ Statement trigger is fired once for a triggering statement.

Classification on the basis of execution time ‡ BEFORE trigger ‡ AFTER trigger .

BEFORE trigger ‡ It executes its trigger action before the triggering statement ‡ It can be used when the trigger action must be executed before the triggering statement completes .

AFTER triggers ‡ Executes the trigger action after triggering statement is executed ‡ It can be used when the triggering statement must be executed before executing the trigger action .

BEGIN EXCEPTION END.Creating a trigger CREATE OR REPLACE TRIGGER TriggerName BEFORE/AFTER DELETE/INSERT/UPDATE OF ColumnName ON TableName FOR EACH ROW WHEN condition DECLARE var and contt delaration. .

EXAMPLE ‡ Write a prog to create a trigger which will tell about the operation performed on the student table .

.program Create or Replace Trigger Opr Before INSERT or UPDATE or DELETE ON STUDENT BEGIN IF INSERTING THEN dbms_output. ELSE UPDATING THEN dbms_output. END.put_line( Operation performed is update ). END IF.put_line( Operation performed is INSERT ). ELSE dbms_output.put_line( Operation performed is DELETE ).

.Enabling or Disabling Triggers ‡ For disabling the trigger: SQL> ALTER TRIGGER TRIGGERNAME Disable. Example: SQL> Alter Trigger check Disable.

Disabling all the triggers of table at once: Syntax: SQL> ALTER Table TableName Disable All Triggers. . ‡ For enabling trigger Syntax: SQL> Alter Trigger TriggerName Enable.Cont..

Dropping a trigger Drop Trigger TriggerName. .

.cursors ‡ A cursor is work area where the result of SQL query is stored at the server side ‡ The content of a cursor are then displayed at the client machine via network ‡ The data stored in a cursor is called active data set .

Steps needs to work with cursor ‡ ‡ ‡ ‡ Declare a cursor Open a cursor Fetch or read from cursor Close a cursor .

Types of cursor ‡ Implicit cursor ‡ Explicit cursor .

opened and closed internally by the oracle engine ‡ The user is not involved in managing the cursor ‡ PL/SQL declares a cursor implicitly for all SQL data manipulation statements .Implicit cursor ‡ It is a work area that is declared.

Explicit cursor ‡ It is a work area that is declared. opened and closed externally by the user ‡ It is also called USER-DEFINED cursor ‡ It is declared in the DECLARE part of PL/SQL block .

Attributes of cursor ‡ To keep track of current status of cursor. PL/SQL uses some attributes which are common to both implicit and explicit cursor .

FALSE otherwise Returns number of records processed from cursor %NOTFOUND %ROWCOUNT . Returns TRUE if record was fetched successfully. FALSE otherwise.ATTRIBUTES Attribute %ISOPEN %FOUND Meaning Returns TRUE if cursor is open. Returns TRUE if record was not fetched successfully. FALSE otherwise.

.Implicit cursor ‡ Implicit cursor attributes are used to access the information about the status of last INSERT. SQL.e. UPDATE. and DELETE or single row select statement ‡ Implicit cursor uses same set of general attributes but proceeded with cursor name i..

Implicit cursor attributes ‡ SQL%ISOPEN This is always return FALSE because the oracle engine closes the implicit cursor automatically after executing SQL statement. .

IF SQL%FOUND THEN dbms_output. END IF. END .put_line( record updated ).EXAMPLE ‡ Write a PL/SQL block to display a message that whether a record is updated or not using SQL%FOUND and SQL%NOTFOUND.put_line( record not updated ). IF SQL%NOTFOUND THEN dbms_output. END IF. BEGIN Update student set city = pune where rollno=&rollno.

num := SQL%ROWCOUNT. dbms_output.put_line( Row affected = num ). . BEGIN Update student set grade = b where grade= c .To count number of rows affected by update statement DECALRE num number(2). END.

user can explicitly declare a cursor to process the rows ‡ It is declared in the DECLARE section of PL/SQL block ‡ All the general attributes of a cursor are applicable to this cursor .Explicit cursor ‡ When a query returns multiple rows.

Steps in handling explicit cursor ‡ Explicit cursor handling needs following steps to be followed: 1. Declare the cursor in DECLARE part of PL/SQL block 2. fetch data from cursor one row at a time into memory variables and process the data stored in the memory variable as required 4. CLOSE the cursor . Using a loop. EXIT from loop when processing is complete 5. Open the cursor 3.

Declaring a cursor ‡ A cursor must be declared before referencing in other statement ‡ When cursor is declared . it is given a name and is associated with a specific query .

.syntax Cursor CursorName IS SELECT statement. EXAMPLE: Cursor C IS SELECT rollno from student where id = 102 .

. which consist of all the rows that meet the query search criteria SYNTAX: Open CursorName.Opening a cursor ‡ Opening a cursor executes the query and identifies the result set.

Fetching record from cursor ‡ After opening a cursor. EXAMPLE: FETCH C INTO rollno. one row at a time SYNTAX: FETCH CursorName INTO variables. name. FETCH statement is used to load the rows from the result set into the memory variable but. .

.Closing a cursor ‡ It disable the cursor and the result set becomes undefined ‡ Once a cursor is closed it can be reopen again SYNTAX: CLOSE CursorName.

END LOOP. EXIT When C%NOTFOUND. dbms_output. LOOP Fetch C into name. END. . Close C. BEGIN Open C.put_line(name).Write a prog to display the name of the student belonging to CSE branch DECLARE CURSOR C IS select name from student where branch = cse .

subprograms The named PL/SQL code blocks that can accept parameters and can be invoked are called SUBPROGRASMS .

types ‡ Procedures ‡ functions .

‡ Basically procedure is used to perform an action where as function is used to compute a value. ‡ Another difference is that procedure may return no value but function must return a value .procedure ‡ A procedure or a function is a group of SQL and PL/SQL statements that is used to perform a specific task.

Stored procedure ‡ It is a procedure that has been compiled and stored in any of the oracle engines system table ‡ The basic purpose of subprograms is to achieve: 1. Modularity 2. reusability .

which enables us to create new modules without affecting the existing modules 2.modularity ‡ It allow the programmer to divide a program into more than one well defined unit called MODULES ‡ Modularity results in: 1. Maintainability. which makes the modules to be managed easily. . Extensibility.

Reusability ‡ It enables a subprogram to be used in any number of applications .

BEGIN PL/SQL statements. ) IS/AS variable and const declaration. EXCEPTION exception handling statements. procedure procedureName (argument IN/OUT datatype. procedure calling. BEGIN executable statements. EXCEPTION END .Creating procedures DECLARE global variable declaration. END ProcedureName.

Begin Num1:=&Num1 Num2:=&Num2 Multiplication(Num1.procedure calling dbms_output. Num2 IN Number.. .To multiply two numbers using procedure DECLARE Num1 Number(2). Num2 Number(2).Mul).put_line(Mul). Procedure multiplication(Num1 IN Number. END .Num2. Mul OUT Number) IS BEGIN Mul:=Num1*Num2. Mul Number(4). End Multiplication.

.Creating a stored procedure Create Or Replace Procedure ProcedureName (Argument IN/OUT/IN OUT Datatype. Exception exception handling statement. Begin PL/SQL statements.) IS/AS Variable and constant declaration. End.. .

Num2 IN Number. Sum OUT Number)IS Begin Sum:=Num1+Num2.Stored procedure to add two numbers Create Or Replace Procedure Addition(Num1 IN Number. . End.

Sum Number(2).Display sum of two numbers by calling the addition stored procedure Declare Num1 Number(2). Num2:=&Num2. Num2 Number(2). dbms_output. End.put_line( Addition is ||Sum). Begin Num1:=&Num1.Num2. Addition(Num1. .Sum).

) Return DataType IS/AS var and const declaration. Exception End FunctionName. End.. Function calling. Begin PL/SQL Statements. . Begin executable statements. .Creating a function Declare Global Variable Declaration. Function FunctionName (Argument IN Datatype.

Deleting stored procedure Drop Procedure ProcedureName. .

Package body . constants.packages ‡ A package is an oracle object which is used to bundle various objects like variables. Package specification 2. cursor and subprograms ‡ A package has two parts: 1.

cursors and subprograms ‡ Body defines cursor and subprograms and thus implement the specification . constants..Cont. ‡ Specification declares the variables.

Advantages of package ‡ Package loads multiple objects into memory in one go. ‡ Packages allow the overloading of procedures and functions. ‡ Packages are easy to understand and the interface between packages are simple. ‡ Packages enhance the code reusability . clear. and well defined. thus it improves the performance.

Procedure ProcedureName(Arg list). . End PackageName.Creating a package Package Specification Create Or Replace Package PackageName AS Function FunctionName(Arg List)Return Datatype.

End PackageName. Exception Exception handling statements. Begin pl/sql statements.Package body Create Or Replace Package Body PackageName AS Function FunctionName(Arg list)Retrn Datatype IS/AS var and const declaration. Exception End ProcedureName. End FunctionName. Begin pl/sql statements. Procedure ProcedureName(arg list)IS/AS variable and const declaration. .

. PackageName.ProcedureName(actual arg).) notation is used as follows: Syntax: PackageName. dot(.Calling objects of package ‡ To call either a function or a procedure contained in a package .FunctionName(actual arg).

.Deleting a package Drop Package PackageName.

Sign up to vote on this title
UsefulNot useful