SlideShare a Scribd company logo
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page1
Pondicherry University Community College
Department of Computer Science
Course : B.Voc [Software Development]
Year : II
Semester : III
Subject : Relational DataBase Management System
Unit IV Study Material
Prepared by
D.GAYA
Assistant Professor,
Department of Computer Science,
Pondicherry University Community College,
Lawspet, Puducherry-08.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page2
Unit IV
PL/SQL: Approach and Advantages – PL/SQL Blocks – Variables – Manipulating Data –
Triggers – Procedures, Functions and Packages – Exception handling.
PL/SQL Introduction
• PL/SQL stands for “Procedural Language extensions to the Structured Query
Language”.
• SQL is a popular language for both querying and updating data in the relational
database management systems (RDBMS).
• PL/SQL engine is in charge of compiling PL/SQL code into byte-code and executes
the executable code.
• The PL/SQL engine can only be installed in an Oracle Database server or an
application development tool such as Oracle Forms.
• Once you submit a PL/SQL block to the Oracle Database server, the PL/SQL engine
collaborates with the SQL engine to compile and execute the code.
• PL/SQL engine runs the procedural elements while the SQL engine processes the
SQL statements.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page3
PL/SQL Block Overview
PL/SQL is a block-structured language whose code is organized into blocks. A
PL/SQL block consists of three sections:
• Declaration sections:
• Executable sections:
• Exception-handling sections.
In a block, the executable section is mandatory while the declaration and exception-
handling sections are optional.
A PL/SQL block has a name. Functions or Procedures is an example of a named
block. A named block is stored into the Oracle Database server and can be reused later.
A block without a name is an anonymous block. An anonymous block is not saved in
the Oracle Database server, so it is just for one-time use. However, PL/SQL anonymous
blocks can be useful for testing purposes.
Structure of a PL/SQL block:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page4
1) Declaration section
A PL/SQL block has a declaration section where you declare variables, allocate
memory for cursors, and define data types.
2) Executable section
• A PL/SQL block has an executable section. An executable section starts with the
keyword BEGIN and ends with the keyword END.
• The executable section must have a least one executable statement, even if it is
the NULL statement which does nothing.
3) Exception-handling section
• A PL/SQL block has an exception-handling section that starts with the
keyword EXCEPTION.
• The exception-handling section is where you catch and handle exceptions raised by
the code in the execution section.
PL/SQL anonymous block example
The following example shows a simple PL/SQL anonymous block with one
executable section.
BEGIN
DBMS_OUTPUT.put_line ('Hello World!');
DBMS_OUTPUT.put_line (10);
END;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page5
The executable section calls the DMBS_OUTPUT.PUT_LINE procedure to display
the "Hello World" message on the screen.
Disadvantages of SQL:
• SQL doesn’t provide the programmers with a technique of condition checking, looping
and branching.
• SQL statements are passed to Oracle engine one at a time which increases traffic and
decreases speed.
• SQL has no facility of error checking during manipulation of data.
Features of PL/SQL:
1. PL/SQL is basically a procedural language, which provides the functionality of decision
making, iteration and many more features of procedural programming languages.
2. PL/SQL can execute a number of queries in one block using single command.
3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and
types, which are stored in the database for reuse by applications.
4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block
known as exception handling block.
5. Applications written in PL/SQL are portable to computer hardware or operating system
where Oracle is operational.
6. PL/SQL Offers extensive error checking.
Differences between SQL and PL/SQL:
SQL PL/SQL
SQL is a single query that is used to
perform DML and DDL operations.
PL/SQL is a block of codes that used to write
the entire program blocks/ procedure/
function, etc.
It is declarative, that defines what needs to
be done, rather than how things need to be
done.
PL/SQL is procedural that defines how the
things needs to be done.
Execute as a single statement. Execute as a whole block.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page6
Mainly used to manipulate data. Mainly used to create an application.
Cannot contain PL/SQL code in it.
It is an extension of SQL, so it can contain
SQL inside it.
PL/SQL data types
Each value in PL/SQL such as a constant, variable and parameter has a data type that
determines the storage format, valid values, and allowed operations.
PL/SQL has two kinds of data types: scalar and composite. The scalar types are types
that store single values such as number, Boolean, character, and datetime whereas the
composite types are types that store multiple values, for example, record and collection.
PL/SQL divides the scalar data types into four families:
• Number
• Boolean
• Character
• Date time
A scalar data type may have subtypes. A subtype is a data type that is a subset of
another data type, which is its base type. A subtype further defines a base type by restricting
the value or size of the base data type.
Numeric data types
The numeric data types represent real numbers, integers, and floating-point numbers.
They are stored as NUMBER, IEEE floating-point storage types
(BINARY_FLOAT and BINARY_DOUBLE), and PLS_INTEGER
• The data types NUMBER, BINARY_FLOAT, and BINARY_DOUBLE are SQL data
types.
• The PLS_INTEGER datatype is specific to PL/SQL. It represents signed 32 bits
integers that range from -2,147,483,648 to 2,147,483,647.
• Because PLS_INTEGER datatype uses hardware arithmetic, they are faster
than NUMBER operations, which uses software arithmetic.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page7
• In addition, PLS_INTEGER values require less storage than NUMBER. Hence, you
should always use PLS_INTEGER values for all calculation in its range to increase
the efficiency of programs.
The PLS_INTEGER datatype has the following predefined subtypes:
PLS_INTEGER
subtypes
Description
NATURAL Represents nonnegative PLS_INTEGER values
NATURALN Represents nonnegative PLS_INTEGER values with NOT
NULL constraint
POSITIVE Represents positive PLS_INTEGER values
POSITIVEN Represents positive PLS_INTEGER value with NOT NULL constraint
SIGNTYPE Represents three values -1, 0, or 1, which are useful for tri-state logic
programming
SIMPLE_INTEGER Represents PLS_INTEGER values with NOT NULL constraint.
Boolean data type
The BOOLEAN datatype has three data values: TRUE, FALSE, and NULL. Boolean
values are typically used in control flow structure such as IF-THEN, CASE, and loop
statements like LOOP, FOR LOOP, and WHILE LOOP.
SQL does not have the BOOLEAN data type, therefore, you cannot:
• Assign a BOOLEAN value to a table column.
• Select the value from a table column into a BOOLEAN variable.
• Use a BOOLEAN value in a SQL function.
• Use a BOOLEAN expression in a SQL statement.
• Use a BOOLEAN value in
the DBMS_OUTPUT.PUTLINE and DBMS_OUTPUT.PUT subprograms.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page8
Character data types
The character data types represent alphanumeric text. PL/SQL uses the SQL character
data types such as CHAR, VARCHAR2, LONG, RAW, LONG RAW, ROWID,
and UROWID.
• CHAR(n) is a fixed-length character type whose length is from 1 to 32,767 bytes.
• VARCHAR2(n) is varying length character data from 1 to 32,767 bytes.
Datetime data types
The datetime data types represent dates, timestamp with or without time zone and
intervals. PL/SQL datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH
TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL YEAR TO
MONTH, and INTERVAL DAY TO SECOND.
Data type synonyms
Data types have synonyms for compatibility with non-Oracle data sources such as
IBM Db2, SQL Server. And it is not a good practice to use data type synonym unless you are
accessing a non-Oracle Database.
Data Type Synonyms
NUMBER DEC, DECIMAL, DOUBLE PRECISION, FLOAT, INTEGER,
INT, NUMERIC, REAL, SMALLINT
CHAR CHARACTER, STRING
VARCHAR2VARCHAR
PL/SQL Variables
In PL/SQL, a variable is named storage location that stores a value of a particular data
type. The value of the variable changes through the program. Before using a variable, you
must declare it in the declaration section of a block.
Declaring variables
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page9
The syntax for a variable declaration is as follows:
variable_name datatype [NOT NULL] [:= initial_value];
In this syntax:
• First, specify the name of the variable. The name of the variable should be as
descriptive as possible, e.g., l_total_sales, l_credit_limit, and l_sales_revenue.
• Second, choose an appropriate data type for the variable, depending on the kind of
value which you want to store, for example, number, character, Boolean, and datetime.
By convention, local variable names should start with l_ and global variable names
should have a prefix of g_ .
The following example declares three variables l_total_sales, l_credit_limit,
and l_contact_name:
DECLARE
l_total_sales NUMBER(15,2);
l_credit_limit NUMBER (10,0);
l_contact_name VARCHAR2(255);
BEGIN
NULL;
END;
Default values
PL/SQL allows you to set a default value for a variable at the declaration time. To
assign a default value to a variable, you use the assignment operator (:=) or
the DEFAULT keyword.
The following example declares a variable named l_product_name with an initial
value 'Laptop':
DECLARE
l_product_name VARCHAR2( 100 ) := 'Laptop';
BEGIN
NULL;
END;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page10
It is equivalent to the following block:
DECLARE
l_product_name VARCHAR2(100) DEFAULT 'Laptop';
BEGIN
NULL;
END;
In this example, instead of using the assignment operator := , we used
the DEFAULT keyword to initialize a variable.
NOT NULL constraint
If you impose the NOT NULL constraint on a value, then the variable cannot accept a
NULL value. Besides, a variable declared with the NOT NULL must be initialized with a
non-null value. Note that PL/SQL treats a zero-length string as a NULL value.
The following example first declares a variable named l_shipping_status with
the NOT NULL constraint. Then, it assigns the variable a zero-length string.
DECLARE
l_shipping_status VARCHAR2( 25 ) NOT NULL := 'Shipped';
BEGIN
l_shipping_status := '';
END;
PL/SQL issued the following error:
ORA-06502: PL/SQL: numeric or value error
Because the variable l_shipping_status declared with the NOT NULL constraint, it
could not accept a NULL value or zero-length string in this case.
Variable assignments
To assign a value to a variable, you use the assignment operator (:=), for example:
DECLARE
l_customer_group VARCHAR2(100) := 'Silver';
BEGIN
l_customer_group := 'Gold';
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page11
DBMS_OUTPUT.PUT_LINE(l_customer_group);
END;
You can assign a value of a variable to another as shown in the following example:
DECLARE
l_business_parter VARCHAR2(100) := 'Distributor';
l_lead_for VARCHAR2(100);
BEGIN
l_lead_for := l_business_parter;
DBMS_OUTPUT.PUT_LINE(l_lead_for);
END;
Manipulating Data in PL/SQL
Data Manipulation Language commands to exercise data operations in the database.
Data operations can be populating the database tables with the application or business data,
modifying the data and removing the data from the database, whenever required. Besides the
data operations, there are set of commands which are used to control these operations
DML stands for Data Manipulation Language. These statements are mainly used to
perform the manipulation activity. It deals with the below operations.
• Data Insertion
• Data Update
• Data Deletion
• Data Selection
In PL/SQL, we can do the data manipulation only by using the SQL commands.
Data Insertion
In PL/SQL, we can insert the data into any table using the SQL command INSERT
INTO. This command will take the table name, table column and column values as the input
and insert the value in the base table.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page12
The INSERT command can also take the values directly from another table using
'SELECT' statement rather than giving the values for each column. Through 'SELECT'
statement, we can insert as many rows as the base table contains.
Syntax:
BEGIN
INSERT INTO <table_name>(<column1 >,<column2>,...<column_n>)
VALUES(<valuel><value2>,...:<value_n>);
END;
The above syntax shows the INSERT INTO command. The table name and values are
a mandatory fields, whereas column names are not mandatory if the insert statements have
values for all the column of the table.
The keyword 'VALUES' is mandatory if the values are given separately as shown
above.
Syntax:
BEGIN
INSERT INTO <table_name>(<columnl>,<column2>,...,<column_n>)
SELECT <columnl>,<column2>,.. <column_n> FROM <table_name2>;
END;
The above syntax shows the INSERT INTO command that takes the values directly
from the <table_name2> using the SELECT command.
The keyword 'VALUES' should not be present in this case as the values are not given
separately.
Data Update
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page13
Data update simply means an update of the value of any column in the table. This can
be done using 'UPDATE' statement. This statement takes the table name, column name and
value as the input and updates the data.
Syntax:
BEGIN
UPDATE <table_name>
SET
<columnl>=<VALUE1>,<column2>=<value2>,<column_n>=<value_n>
WHERE <condition that uniquely identifies the record that needs to be
update>;
END;
The above syntax shows the UPDATE. The keyword 'SET' instruct that PL/SQL
engine to update the value of the column with the value given.
'WHERE' clause is optional. If this clause is not given, then the value of the
mentioned column in the entire table will be updated.
Data Deletion
Data deletion means to delete one full record from the database table. The 'DELETE'
command is used for this purpose.
Syntax:
BEGIN
DELETE
FROM
<table_name>
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page14
WHERE <condition that uniquely identifies the record that needs to be
update>;
END;
The above syntax shows the DELETE command. The keyword 'FROM' is optional
and with or without 'FROM' clause the command behaves in the same way.
'WHERE' clause is optional. If this clause is not given, then the entire table will be
deleted.
Data Selection
Data projection/fetching means to retrieve the required data from the database table.
This can be achieved by using the command 'SELECT' with 'INTO' clause. The 'SELECT'
command will fetch the values from the database, and 'INTO' clause will assign these values
to the local variable of the PL/SQL block.
Below are the points that need to be considered in 'SELECT' statement.
• 'SELECT' statement should return only one record while using 'INTO' clause as one
variable can hold only one value. If the 'SELECT' statement returns more than one
value than 'TOO_MANY_ROWS' exception will be raised.
• 'SELECT' statement will assign the value to the variable in the 'INTO' clause, so it
needs to get at least one record from the table to populate the value. If it didn't get any
record, then the exception 'NO_DATA_FOUND' is raised.
• The number of columns and their datatype in 'SELECT' clause should match with the
number of variables and their datatypes in the 'INTO' clause.
• The values are fetched and populated in the same order as mentioned in the statement.
• 'WHERE' clause is optional that allows to having more restriction on the records that
are going to be fetched.
• 'SELECT' statement can be used in the 'WHERE' condition of other DML statements
to define the values of the conditions.
• The 'SELECT' statement when using 'INSERT', 'UPDATE', 'DELETE' statements
should not have 'INTO' clause as it will not populate any variable in these cases.
Syntax:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page15
BEGIN
SELECT <columnl>,..<column_n> INTO <vanable 1 >,. .<variable_n>
FROM <table_name>
WHERE <condition to fetch the required records>;
END;
The above syntax shows the SELECT-INTO command. The keyword 'FROM' is
mandatory that identifies the table name from which the data needs to be fetched.
'WHERE' clause is optional. If this clause is not given, then the data from the entire
table will be fetched.
Example 1: In this example, we are going to see how to perform DML operations in PL/SQL.
We are going to insert the below four records into emp table.
EMP_NAME EMP_NO SALARY MANAGER
BBB 1000 25000 AAA
XXX 1001 10000 BBB
YYY 1002 10000 BBB
ZZZ 1003 7500 BBB
Then we are going to update the salary of 'XXX' to 15000, and we are going to delete
the employee record 'ZZZ'. Finally, we are going to project the details of the employee 'XXX'.
DECLARE
l_emp_name VARCHAR2(250);
l_emp_no NUMBER;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page16
l_salary NUMBER;
l_manager VARCHAR2(250);
BEGIN
//Data Insert
INSERT INTO emp(emp_name,emp_no,salary,manager)
VALUES(‘BBB’,1000,25000,’AAA’);
INSERT INTO emp(emp_name,emp_no,salary,manager)
VALUES('XXX',1001,10000,’BBB);
INSERT INTO emp(emp_name,emp_no,salary,managed
VALUES(‘YYY',1002,10000,'BBB');
INSERT INTO emp(emp_name,emp_no,salary,manager)
VALUES(‘ZZZ',1003,7500,'BBB'):
COMMIT; // TCL Command
Dbms_output.put_line(‘Values Inserted');
//Data Update and Delete
UPDATE EMP
SET salary=15000
WHERE emp_name='XXX';
COMMIT;
Dbms_output.put_line(‘Values Updated');
DELETE emp WHERE emp_name='ZZZ';
COMMIT:
Dbms_output.put_line('Values Deleted );
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page17
//Display Statement
SELECT emp_name,emp_no,salary,manager INTO
l_emp_name,l_emp_no,l_salary,l_manager FROM emp WHERE
emp_name='XXX';
Dbms_output.put line(‘Employee Detail’);
Dbms_output.put line(‘----------------------’);
Dbms_output.put_line(‘Employee Name:‘||l_emp_name);
Dbms_output.put_line(‘Employee Number:‘||l_emp_no);
Dbms_output.put_line (‘Employee Salary:‘||l_salary);
Dbms output.put line(‘Emplovee Manager Name:‘||l_manager):
END;
/
Output:
Values Inserted
Values Updated
Values Deleted
Employee Detail
---------------------
Employee Name:XXX
Employee Number:1001
Employee Salary:15000
Employee Manager Name:BBB
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page18
SQL>select * from EMP;
EMP_NAME EMP_NO SALARY MANAGER
BBB 1000 25000 AAA
BBB’ ,1000, 25000,’ AAA’
XXX 1001 15000 BBB
YYY 1002 10000 BBB
PL/SQL Procedures
PL/SQL procedures create using CREATE PROCEDURE statement. The major
difference between PL/SQL function or procedure, function return always value whereas
procedure may or may not return value.
When you create a function or procedure, you have to define IN/OUT/INOUT
parameters parameters.
• IN: IN parameter referring to the procedure or function and allow to overwritten the
value of parameter.
• OUT: OUT parameter referring to the procedure or function and allow to overwritten
the value of parameter.
• IN OUT: Both IN OUT parameter referring to the procedure or function to pass both
IN OUT parameter, modify/update by the function or procedure and also get returned.
IN/OUT/INOUT parameters you define in procedure argument list that get returned back
to a result. When you create the procedure default IN parameter is passed in argument list. It's
means value is passed but not returned. Explicitly you have define OUT/IN OUT parameter
in argument list.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page19
PL/SQL Procedure Syntax
CREATE [OR REPLACE] PROCEDURE [SCHEMA..] procedure_name
[ (parameter [,parameter]) ]
IS
[declaration_section
variable declarations;
constant declarations;
]
BEGIN
[executable_section
PL/SQL execute/subprogram body
]
[EXCEPTION]
[exception_section
PL/SQL Exception block
]
END [procedure_name];
/
PL/SQL Procedure Example
In this example we are creating a procedure to pass employee number argument and get that
employee information from table. We have emp1 table having employee information,
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page20
EMP_NO EMP_NAME EMP_DEPT EMP_SALARY
1 Forbs ross Web Developer 45k
2 marks jems Program Developer 38k
3 Saulin Program Developer 34k
4 Zenia Sroll Web Developer 42k
Create PROCEDURE
In this example passing IN parameter (no) and inside procedure SELECT ... INTO
statement to get the employee information.
pro1.sql
SQL>dit pro1
CREATE or REPLACE PROCEDURE pro1(no in number,temp out emp1%rowtype)
IS
BEGIN
SELECT * INTO temp FROM emp1 WHERE eno = no;
END;
/
Execute PROCEDURE
After write the PL/SQL Procedure you need to execute the procedure.
SQL>@pro1
Procedure created.
PL/SQL procedure successfully completed.
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page21
PL/SQL Program to Calling Procedure
This program (pro) call the above define procedure with pass employee number and get that
employee information.
pro.sql
SQL>edit pro
DECLARE
temp emp1%rowtype;
no number :=&no;
BEGIN
pro1(no,temp);
dbms_output.put_line(temp.eno||' '||
temp.ename||' '||
temp.edept||' '||
temp.esalary||' '||);
END;
/
SQL>@pro
no number &n=2
2 marks jems Program Developer 38K
PL/SQL procedure successfully completed.
PL/SQL Drop Procedure
You can drop PL/SQL procedure using DROP PROCEDURE statement,
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page22
Syntax
DROP PROCEDURE procedure_name;
Example
SQL>DROP PROCEDURE pro1;
Procedure dropped.
PL/SQL Functions
PL/SQL functions block create using CREATE FUNCTION statement. The major difference
between PL/SQL function or procedure, function return always value where as procedure
may or may not return value.
When you create a function or procedure, you have to define IN/OUT/INOUT parameters
parameters.
• IN: IN parameter referring to the procedure or function and allow to overwritten the
value of parameter.
• OUT: OUT parameter referring to the procedure or function and allow to overwritten
the value of parameter.
• IN OUT: Both IN OUT parameter referring to the procedure or function to pass both
IN OUT parameter, modify/update by the function or procedure and also get returned.
IN/OUT/INOUT parameters you define in function argument list that get returned back to a
result. When you create the function default IN parameter is passed in argument list. It's
means value is passed but not returned. Explicitly you have define OUT/IN OUT parameter
in argument list.
PL/SQL Functions Syntax
CREATE [OR REPLACE] FUNCTION [SCHEMA..]
function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page23
IS | AS
[declaration_section
variable declarations;
constant declarations;
]
BEGIN
[executable_section
PL/SQL execute/subprogram body
]
[EXCEPTION]
[exception_section
PL/SQL Exception block
]
END [function_name];
/
PL/SQL Function Example
EMP_NO EMP_NAME EMP_DEPT EMP_SALARY
1 Forbs ross Web Developer 45k
2 marks jems Program Developer 38k
3 Saulin Program Developer 34k
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page24
In this example we are creating a function to pass employee number and get that
employee name from table. We have emp1 table having employee information,
Create Function
So lets start passing IN parameter (no). Return datatype set varchar2. Now inside function
SELECT ... INTO statement to get the employee name.
fun1.sql
SQL>edit fun1
CREATE or REPLACE FUNCTION fun1(no in number)
RETURN varchar2
IS
name varchar2(20);
BEGIN
select ename into name from emp1 where eno = no;
return name;
END;
/
Execute Function
After write the PL/SQL function you need to execute the function.
SQL>@fun1
Function created.
PL/SQL procedure successfully completed.
PL/SQL Program to Calling Function
4 Zenia Sroll Web Developer 42k
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page25
This program call the above define function with pass employee number and get that
employee name.
fun.sql
SQL>edit fun
DECLARE
no number :=&no;
name varchar2(20);
BEGIN
name := fun1(no);
dbms_output.put_line('Name:'||' '||name);
end;
/
Result
SQL>@fun
no number &n=2
Name: marks jems
PL/SQL procedure successfully completed.
PL/SQL Drop Function
You can drop PL/SQL function using DROP FUNCTION statements.
Syntax
DROP FUNCTION function_name;
Example
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page26
SQL>DROP FUNCTION fun1;
Function dropped.
PL/SQL Triggers
Trigger automatically associated with DML statement, when DML statement execute trigger
implicitly execute.You can create trigger using the CREATE TRIGGER statement.
Component of Trigger
• Triggering SQL statement: SQL DML (INSERT, UPDATE and DELETE)
statement that execute and implicitly called trigger to execute.
• Trigger Action: When the triggering SQL statement is execute, trigger automatically
call and PL/SQL trigger block execute.
• Trigger Restriction: We can specify the condition inside trigger to when trigger is
fire.
Type of Triggers
• BEFORE Trigger:
o BEFORE trigger execute before the triggering DML statement (INSERT,
UPDATE, DELETE) execute. Triggering SQL statement is may or may not
execute, depending on the BEFORE trigger conditions block.
• AFTER Trigger:
o AFTER trigger execute after the triggering DML statement (INSERT,
UPDATE, DELETE) executed. Triggering SQL statement is execute as soon
as followed by the code of trigger before performing Database operation.
• ROW Trigger:
o ROW trigger fire for each and every record which are performing INSERT,
UPDATE, DELETE from the database table. If row deleting is define as
trigger event, when trigger file, deletes the five rows each times from the table.
• Statement Trigger:
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page27
o Statement trigger fire only once for each statement. If row deleting is define as
trigger event, when trigger file, deletes the five rows at once from the table.
PL/SQL Triggers Syntax
PL/SQL trigger define using CREATE TRIGGER statement.
CREATE [OR REPLACE] TRIGGER trigger_name
BEFORE | AFTER
[INSERT, UPDATE, DELETE [COLUMN NAME..]
ON table_name
Referencing [ OLD AS OLD | NEW AS NEW ]
FOR EACH ROW | FOR EACH STATEMENT [ WHEN Condition ]
DECLARE
[declaration_section
variable declarations;
constant declarations;
]
BEGIN
[executable_section
PL/SQL execute/subprogram body
]
EXCEPTION
[exception_section
PL/SQL Exception block
]
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page28
END;
Syntax Description
o CREATE [OR REPLACE] TRIGGER trigger_name: Create a trigger with the given
name. If already have overwrite the existing trigger with defined same name.
o BEFORE | AFTER : Indicates when the trigger get fire. BEFORE trigger execute
before when statement execute before. AFTER trigger execute after the statement
execute.
o [INSERT, UPDATE, DELETE [COLUMN NAME..]: Determines the performing
trigger event. You can define more then one triggering event separated by OR
keyword.
o ON table_name: Define the table name to performing trigger event.
o Referencing [ OLD AS OLD | NEW AS NEW ]: Give referencing to a old and new
values of the data. :old means use existing row to perform event and :new means use
executing new row to perform event. You can set referencing names user define name
from old (or new).
You can't referencing old values when inserting a record, or new values when deleting
a record, because It's does not exist.
o FOR EACH ROW | FOR EACH STATEMENT: Trigger must fire when each row
gets Affected (ROW Trigger). and fire only once when the entire sql statement is
execute (STATEMENT Trigger).
o WHEN Condition: Optional. Use only for row level trigger. Trigger fire when
specified condition is satisfy.
PL/SQL Triggers Example
You can make your own trigger using trigger syntax referencing. Here are fewer trigger
example.
Inserting Trigger
This trigger execute BEFORE to convert ename field lowercase to uppercase.
CREATE or REPLACE TRIGGER trg1
BEFORE
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page29
INSERT ON emp1
FOR EACH ROW
BEGIN
:new.ename := upper(:new.ename);
END;
/
Restriction to Deleting Trigger
This trigger is preventing to deleting row.
Delete Trigger Example
CREATE or REPLACE TRIGGER trg1
AFTER
DELETE ON emp1
FOR EACH ROW
BEGIN
IF :old.eno = 1 THEN
raise_application_error(-2019, 'You can't delete this row');
END IF;
END;
/
Delete Trigger Result
SQL>delete from emp1 where eno = 1;
Error Code: 2019
Error Name: You can't delete this row
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page30
PL/SQL Packages
PL/SQL Packages is schema object and collection of related data type (variables,
constants), cursors, procedures, functions are defining within a single context.
Package are divide into two part,
• Package Specification
• Package Body
Package specification block you can define variables, constants, exceptions and package
body you can create procedure, function, subprogram.
PL/SQL Package Advantages
• You can create package to store all related functions and procedures are grouped
together into single unit called packages.
• Package are reliable to granting a privileges.
• All function and procedure within a package can share variable among them.
• Package are support overloading to overload functions and procedures.
• Package are improve the performance to loading the multiple object into memory at
once, therefore, subsequent calls to related program doesn't required to calling
physically I/O.
• Package are reduce the traffic because all block execute all at once.
PL/SQL Specification:
This contain the list of variables, constants, functions, procedure names which are the
part of the package. PL/SQL specification are public declaration and visible to a program.
Defining Package Specification Syntax
CREATE [OR REPLACE] PACKAGE package_name
IS | AS
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page31
[variable_declaration ...]
[constant_declaration ...]
[exception_declaration ...]
[cursor_specification ...]
[PROCEDURE [Schema..] procedure_name
[ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ]
]
[FUNCTION [Schema..] function_name
[ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ]
RETURN return_datatype
]
END [package_name];
PL/SQL Body:
This contains the actual PL/SQL statement code implementing the logics of functions,
procedures which are you already before declare in "Package specification".
Creating Package Body Syntax
CREATE [OR REPLACE] PACKAGE BODY package_name
IS | AS
[private_variable_declaration ...]
[private_constant_declaration ...]
BEGIN
[initialization_statement]
[PROCEDURE [Schema..] procedure_name
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page32
[ (parameter [,parameter]) ]
IS | AS
variable declarations;
constant declarations;
BEGIN
statement(s);
EXCEPTION
WHEN ...
END
]
[FUNCTION [Schema..] function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
variable declarations;
constant declarations;
BEGIN
statement(s);
EXCEPTION
WHEN ...
END
]
[EXCEPTION
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page33
WHEN built-in_exception_name_1 THEN
User defined statement (action) will be taken;
]
END;
/
PL/SQL Package Example
PL/SQL Package example step by step explain to you, you are create your own
package using this reference example. We have emp1 table having employee information,
EMP_NO EMP_NAME EMP_DEPT EMP_SALARY
1 Forbs ross Web Developer 45k
2 marks jems Program Developer 38k
3 Saulin Program Developer 34k
4 Zenia Sroll Web Developer 42k
Package Specification
Create Package specification code for defining procedure, function IN or OUT parameter and
execute package specification program.
CREATE or REPLACE PACKAGE pkg1
IS | AS
PROCEDURE pro1
(no in number, name out varchar2);
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page34
FUNCTION fun1
(no in number)
RETURN varchar2;
END;
/
Package Body
Create Package body code for implementing procedure or function that are defined
package specification. Once you implement execute this program.
CREATE or REPLACE PACKAGE BODY pkg1
IS
PROCEDURE pro1(no in number,info our varchar2)
IS
BEGIN
SELECT * INTO temp FROM emp1 WHERE eno = no;
END;
FUNCTION fun1(no in number) return varchar2
IS
name varchar2(20);
BEGIN
SELECT ename INTO name FROM emp1 WHERE eno = no;
RETURN name;
END;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page35
END;
/
Pl/SQL Program calling Package
Now we have a one package pkg1, to call package defined function, procedures also
pass the parameter and get the return result.
pkg_prg.sql
DECLARE
no number := &no;
name varchar2(20);
BEGIN
pkg1.pro1(no,info);
dbms_output.put_line('Procedure Result');
dbms_output.put_line(info.eno||' '||
info.ename||' '||
info.edept||' '||
info.esalary||' '||);
dbms_output.put_line('Function Result');
name := pkg1.fun1(no);
dbms_output.put_line(name);
END;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page36
/
Result
Now execute the above created pkg_prg.sql program to asking which user information you
want to get, you put user id and give information.
SQL>@pkg_prg
no number &n=2
Procedure Result
2 marks jems Program Developer 38K
Function Result
marks jems
PL/SQL procedure successfully completed.
PL/SQL Exception Handling
• PL/SQL exceptions are predefined and raised automatically into oracle engine when
any error occur during a program.
• Each and every error has defined a unique number and message. When warning/error
occur in program it's called an exception to contains information about the error.
• In PL/SQL built in exceptions or you make user define exception. Examples of built-
in type (internally) defined exceptions division by zero, out of memory. Some
common built-in exceptions have predefined names such as ZERO_DIVIDE and
STORAGE_ERROR.
• Normally when exception is fire, execution stops and control transfers to the
exception-handling part of your PL/SQL block. Internal exceptions are raised
implicitly (automatically) by the run-time system. User-defined exceptions must be
raised explicitly by RAISE statements, which are also raise predefined exceptions.
PL/SQL exceptions consist following three,
• Exception Type
• Error Code
• Error Message
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page37
Syntax
DECLARE
declaration statement(s);
BEGIN
statement(s);
EXCEPTION
WHEN built-in_exception_name_1 THEN
User defined statement (action) will be taken;
WHEN built-in_exception_name_2 THEN
User defined statement (action) will be taken;
END;
Example
builtin_exp.sql
SQL>edit buitin_exp
DECLARE
temp enum%rowtype;
BEGIN
SELECT * INTO temp FROM enum WHERE eno=3;
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line("Table haven't data");
END;
/
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page38
Result
SQL>@buitin_exp
Table haven't data
PL/SQL procedure successfully operation.
PL/SQL User Defined Exception
PL/SQL user defined exception to make your own exception. PL/SQL give you
control to make your own exception base on oracle rules. User define exception must be
declare yourself and RAISE statement to raise explicitly.
How to Define Exception
Declare exception
You must have to declare user define exception name in DECLARE block.
user_define_exception_name EXCEPTION;
Exception and Variable both are same way declaring but exception use for store error
condition not a storage item.
RAISE exception
RAISE statement to raised defined exception name and control transfer to a EXCEPTION
block.
RAISE user_define_exception_name;
Implement exception condition
In PL/SQL EXCEPTION block add WHEN condition to implement user define action.
WHEN user_define_exception_name THEN
User defined statement (action) will be taken;
Syntax
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page39
Check this user defined exception syntax,
DECLARE
user_define_exception_name EXCEPTION;
BEGIN
statement(s);
IF condition THEN
RAISE user_define_exception_name;
END IF;
EXCEPTION
WHEN user_define_exception_name THEN
User defined statement (action) will be taken;
END;
Example
user_exp.sql
SQL>edit user_exp
DECLARE
myex EXCEPTION;
i NUMBER;
BEGIN
FOR i IN (SELECT * FROM enum) LOOP
IF i.eno = 3 THEN
RAISE myex;
END IF;
D.GAYA, Assistant Professor, Department of Computer Science, PUCC.
Page40
END LOOP;
EXCEPTION
WHEN myex THEN
dbms_output.put.line('Employee number already exist in enum table.');
END;
/
Result
SQL>@user_exp
Employee number already exist in enum table.
Ad

More Related Content

What's hot (20)

認証の課題とID連携の実装 〜ハンズオン〜
認証の課題とID連携の実装 〜ハンズオン〜認証の課題とID連携の実装 〜ハンズオン〜
認証の課題とID連携の実装 〜ハンズオン〜
Masaru Kurahayashi
 
Skills for Python Full Stack Developer.pptx
Skills for Python Full Stack Developer.pptxSkills for Python Full Stack Developer.pptx
Skills for Python Full Stack Developer.pptx
FirstBitSolutions
 
Python - the basics
Python - the basicsPython - the basics
Python - the basics
University of Technology
 
【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~
【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~
【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~
Developers Summit
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
Intelligo Technologies
 
Flutter
FlutterFlutter
Flutter
Himanshu Singh
 
Compiler vs interpreter
Compiler vs interpreterCompiler vs interpreter
Compiler vs interpreter
Paras Patel
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
Shubham Sharma
 
Java
JavaJava
Java
s4al_com
 
OAuth認証について
OAuth認証についてOAuth認証について
OAuth認証について
Yoshifumi Sato
 
kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-
kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-
kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-
JOYZO
 
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
Masaru Kurahayashi
 
Assemblers
AssemblersAssemblers
Assemblers
Dattatray Gandhmal
 
Flutter Festival - Intro Session
Flutter Festival - Intro SessionFlutter Festival - Intro Session
Flutter Festival - Intro Session
Google Developer Students Club NIT Silchar
 
Macro and Preprocessor in c programming
 Macro and  Preprocessor in c programming Macro and  Preprocessor in c programming
Macro and Preprocessor in c programming
ProfSonaliGholveDoif
 
Java(Polymorphism)
Java(Polymorphism)Java(Polymorphism)
Java(Polymorphism)
harsh kothari
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data Types
Micheal Ogundero
 
Pre processor directives in c
Pre processor directives in cPre processor directives in c
Pre processor directives in c
baabtra.com - No. 1 supplier of quality freshers
 
C Programming Unit-1
C Programming Unit-1C Programming Unit-1
C Programming Unit-1
Vikram Nandini
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D array
Gem WeBlog
 
認証の課題とID連携の実装 〜ハンズオン〜
認証の課題とID連携の実装 〜ハンズオン〜認証の課題とID連携の実装 〜ハンズオン〜
認証の課題とID連携の実装 〜ハンズオン〜
Masaru Kurahayashi
 
Skills for Python Full Stack Developer.pptx
Skills for Python Full Stack Developer.pptxSkills for Python Full Stack Developer.pptx
Skills for Python Full Stack Developer.pptx
FirstBitSolutions
 
【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~
【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~
【15-B-7】無意味なアラートからの脱却 ~ Datadogを使ってモダンなモニタリングを始めよう ~
Developers Summit
 
Compiler vs interpreter
Compiler vs interpreterCompiler vs interpreter
Compiler vs interpreter
Paras Patel
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
Shubham Sharma
 
OAuth認証について
OAuth認証についてOAuth認証について
OAuth認証について
Yoshifumi Sato
 
kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-
kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-
kintoneで実践するIoTハンズオン -90分で挑戦!kintone & AWS IoT連携-
JOYZO
 
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
OpenID Connect 入門 〜コンシューマーにおけるID連携のトレンド〜
Masaru Kurahayashi
 
Macro and Preprocessor in c programming
 Macro and  Preprocessor in c programming Macro and  Preprocessor in c programming
Macro and Preprocessor in c programming
ProfSonaliGholveDoif
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data Types
Micheal Ogundero
 
13. Pointer and 2D array
13. Pointer  and  2D array13. Pointer  and  2D array
13. Pointer and 2D array
Gem WeBlog
 

Similar to Unit 4 rdbms study_material (20)

Unit 4 plsql
Unit 4  plsqlUnit 4  plsql
Unit 4 plsql
DrkhanchanaR
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
shivanikaale214
 
PL/SQL is a block structured language that enables developers to combine the ...
PL/SQL is a block structured language that enables developers to combine the ...PL/SQL is a block structured language that enables developers to combine the ...
PL/SQL is a block structured language that enables developers to combine the ...
renuka b
 
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdfPROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
rajeswaria21
 
Procedural Language/Structured Query Language
Procedural Language/Structured Query LanguageProcedural Language/Structured Query Language
Procedural Language/Structured Query Language
allinzone1
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptxCh as pbdasdadssadsadsadasdasdasdas fdt .pptx
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
sharmilasatishpore
 
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbchapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
hhhhhcccc25
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
Pranab Dasgupta
 
Chapter 1
Chapter 1Chapter 1
Chapter 1
pooja_123
 
Pl sql
Pl sqlPl sql
Pl sql
Meenakshi Chandrasekaran
 
Pl sql
Pl sqlPl sql
Pl sql
Priya Laxmanan
 
Pl sql
Pl sqlPl sql
Pl sql
chaitanyanaredla
 
Pl sql-ch1
Pl sql-ch1Pl sql-ch1
Pl sql-ch1
Mukesh Tekwani
 
Chapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbb
Chapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbbChapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbb
Chapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbb
hhhhhcccc25
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
GunavathyShanmuganat
 
Chapter8 pl sql
Chapter8 pl sqlChapter8 pl sql
Chapter8 pl sql
Jafar Nesargi
 
Unit 3 rdbms study_materials-converted
Unit 3  rdbms study_materials-convertedUnit 3  rdbms study_materials-converted
Unit 3 rdbms study_materials-converted
gayaramesh
 
Unit4_DBMS.pptx
Unit4_DBMS.pptxUnit4_DBMS.pptx
Unit4_DBMS.pptx
ssuserabaa40
 
pl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledgepl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledge
Masood Khan
 
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docxWhat does PL_SQL stand for and what is the functioning of PL_SQL.docx
What does PL_SQL stand for and what is the functioning of PL_SQL.docx
shivanikaale214
 
PL/SQL is a block structured language that enables developers to combine the ...
PL/SQL is a block structured language that enables developers to combine the ...PL/SQL is a block structured language that enables developers to combine the ...
PL/SQL is a block structured language that enables developers to combine the ...
renuka b
 
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdfPROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
PROCEDURAL LANGUAGE/ STRUCTURED QUERY LANGUAGE.pdf
rajeswaria21
 
Procedural Language/Structured Query Language
Procedural Language/Structured Query LanguageProcedural Language/Structured Query Language
Procedural Language/Structured Query Language
allinzone1
 
PL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics CoveredPL/SQL Complete Tutorial. All Topics Covered
PL/SQL Complete Tutorial. All Topics Covered
Danish Mehraj
 
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptxCh as pbdasdadssadsadsadasdasdasdas fdt .pptx
Ch as pbdasdadssadsadsadasdasdasdas fdt .pptx
sharmilasatishpore
 
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbchapter  1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
chapter 1.pdfbbbbbbbbbbbbbbbbbbbbbbbbbb
hhhhhcccc25
 
Database management system chapter5
Database management system chapter5Database management system chapter5
Database management system chapter5
Pranab Dasgupta
 
Chapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbb
Chapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbbChapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbb
Chapter 2.pdfbbbbbbbbbbbbbbbbbbbbbbbbbbb
hhhhhcccc25
 
Unit 3 rdbms study_materials-converted
Unit 3  rdbms study_materials-convertedUnit 3  rdbms study_materials-converted
Unit 3 rdbms study_materials-converted
gayaramesh
 
pl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledgepl/sql online Training|sql online Training | iTeknowledge
pl/sql online Training|sql online Training | iTeknowledge
Masood Khan
 
Ad

More from gayaramesh (6)

Unit 1 vb study_materials
Unit 1 vb study_materialsUnit 1 vb study_materials
Unit 1 vb study_materials
gayaramesh
 
Unit1 rdbms study_materials-converted (1) (1)
Unit1 rdbms study_materials-converted (1) (1)Unit1 rdbms study_materials-converted (1) (1)
Unit1 rdbms study_materials-converted (1) (1)
gayaramesh
 
Unit 2 rdbms study_material
Unit 2  rdbms study_materialUnit 2  rdbms study_material
Unit 2 rdbms study_material
gayaramesh
 
Unit 5 rdbms study_material
Unit 5  rdbms study_materialUnit 5  rdbms study_material
Unit 5 rdbms study_material
gayaramesh
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materials
gayaramesh
 
Unit1 rdbms study_materials
Unit1 rdbms study_materialsUnit1 rdbms study_materials
Unit1 rdbms study_materials
gayaramesh
 
Unit 1 vb study_materials
Unit 1 vb study_materialsUnit 1 vb study_materials
Unit 1 vb study_materials
gayaramesh
 
Unit1 rdbms study_materials-converted (1) (1)
Unit1 rdbms study_materials-converted (1) (1)Unit1 rdbms study_materials-converted (1) (1)
Unit1 rdbms study_materials-converted (1) (1)
gayaramesh
 
Unit 2 rdbms study_material
Unit 2  rdbms study_materialUnit 2  rdbms study_material
Unit 2 rdbms study_material
gayaramesh
 
Unit 5 rdbms study_material
Unit 5  rdbms study_materialUnit 5  rdbms study_material
Unit 5 rdbms study_material
gayaramesh
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materials
gayaramesh
 
Unit1 rdbms study_materials
Unit1 rdbms study_materialsUnit1 rdbms study_materials
Unit1 rdbms study_materials
gayaramesh
 
Ad

Recently uploaded (20)

introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
The Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLabThe Gaussian Process Modeling Module in UQLab
The Gaussian Process Modeling Module in UQLab
Journal of Soft Computing in Civil Engineering
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Oil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdfOil-gas_Unconventional oil and gass_reseviours.pdf
Oil-gas_Unconventional oil and gass_reseviours.pdf
M7md3li2
 
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
DATA-DRIVEN SHOULDER INVERSE KINEMATICS YoungBeom Kim1 , Byung-Ha Park1 , Kwa...
charlesdick1345
 
Compiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptxCompiler Design_Lexical Analysis phase.pptx
Compiler Design_Lexical Analysis phase.pptx
RushaliDeshmukh2
 
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdfRICS Membership-(The Royal Institution of Chartered Surveyors).pdf
RICS Membership-(The Royal Institution of Chartered Surveyors).pdf
MohamedAbdelkader115
 
railway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forgingrailway wheels, descaling after reheating and before forging
railway wheels, descaling after reheating and before forging
Javad Kadkhodapour
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
Degree_of_Automation.pdf for Instrumentation and industrial specialist
Degree_of_Automation.pdf for  Instrumentation  and industrial specialistDegree_of_Automation.pdf for  Instrumentation  and industrial specialist
Degree_of_Automation.pdf for Instrumentation and industrial specialist
shreyabhosale19
 
some basics electrical and electronics knowledge
some basics electrical and electronics knowledgesome basics electrical and electronics knowledge
some basics electrical and electronics knowledge
nguyentrungdo88
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Mathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdfMathematical foundation machine learning.pdf
Mathematical foundation machine learning.pdf
TalhaShahid49
 
π0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalizationπ0.5: a Vision-Language-Action Model with Open-World Generalization
π0.5: a Vision-Language-Action Model with Open-World Generalization
NABLAS株式会社
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptxExplainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
Explainable-Artificial-Intelligence-XAI-A-Deep-Dive (1).pptx
MahaveerVPandit
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 

Unit 4 rdbms study_material

  • 1. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page1 Pondicherry University Community College Department of Computer Science Course : B.Voc [Software Development] Year : II Semester : III Subject : Relational DataBase Management System Unit IV Study Material Prepared by D.GAYA Assistant Professor, Department of Computer Science, Pondicherry University Community College, Lawspet, Puducherry-08.
  • 2. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page2 Unit IV PL/SQL: Approach and Advantages – PL/SQL Blocks – Variables – Manipulating Data – Triggers – Procedures, Functions and Packages – Exception handling. PL/SQL Introduction • PL/SQL stands for “Procedural Language extensions to the Structured Query Language”. • SQL is a popular language for both querying and updating data in the relational database management systems (RDBMS). • PL/SQL engine is in charge of compiling PL/SQL code into byte-code and executes the executable code. • The PL/SQL engine can only be installed in an Oracle Database server or an application development tool such as Oracle Forms. • Once you submit a PL/SQL block to the Oracle Database server, the PL/SQL engine collaborates with the SQL engine to compile and execute the code. • PL/SQL engine runs the procedural elements while the SQL engine processes the SQL statements.
  • 3. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page3 PL/SQL Block Overview PL/SQL is a block-structured language whose code is organized into blocks. A PL/SQL block consists of three sections: • Declaration sections: • Executable sections: • Exception-handling sections. In a block, the executable section is mandatory while the declaration and exception- handling sections are optional. A PL/SQL block has a name. Functions or Procedures is an example of a named block. A named block is stored into the Oracle Database server and can be reused later. A block without a name is an anonymous block. An anonymous block is not saved in the Oracle Database server, so it is just for one-time use. However, PL/SQL anonymous blocks can be useful for testing purposes. Structure of a PL/SQL block:
  • 4. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page4 1) Declaration section A PL/SQL block has a declaration section where you declare variables, allocate memory for cursors, and define data types. 2) Executable section • A PL/SQL block has an executable section. An executable section starts with the keyword BEGIN and ends with the keyword END. • The executable section must have a least one executable statement, even if it is the NULL statement which does nothing. 3) Exception-handling section • A PL/SQL block has an exception-handling section that starts with the keyword EXCEPTION. • The exception-handling section is where you catch and handle exceptions raised by the code in the execution section. PL/SQL anonymous block example The following example shows a simple PL/SQL anonymous block with one executable section. BEGIN DBMS_OUTPUT.put_line ('Hello World!'); DBMS_OUTPUT.put_line (10); END;
  • 5. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page5 The executable section calls the DMBS_OUTPUT.PUT_LINE procedure to display the "Hello World" message on the screen. Disadvantages of SQL: • SQL doesn’t provide the programmers with a technique of condition checking, looping and branching. • SQL statements are passed to Oracle engine one at a time which increases traffic and decreases speed. • SQL has no facility of error checking during manipulation of data. Features of PL/SQL: 1. PL/SQL is basically a procedural language, which provides the functionality of decision making, iteration and many more features of procedural programming languages. 2. PL/SQL can execute a number of queries in one block using single command. 3. One can create a PL/SQL unit such as procedures, functions, packages, triggers, and types, which are stored in the database for reuse by applications. 4. PL/SQL provides a feature to handle the exception which occurs in PL/SQL block known as exception handling block. 5. Applications written in PL/SQL are portable to computer hardware or operating system where Oracle is operational. 6. PL/SQL Offers extensive error checking. Differences between SQL and PL/SQL: SQL PL/SQL SQL is a single query that is used to perform DML and DDL operations. PL/SQL is a block of codes that used to write the entire program blocks/ procedure/ function, etc. It is declarative, that defines what needs to be done, rather than how things need to be done. PL/SQL is procedural that defines how the things needs to be done. Execute as a single statement. Execute as a whole block.
  • 6. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page6 Mainly used to manipulate data. Mainly used to create an application. Cannot contain PL/SQL code in it. It is an extension of SQL, so it can contain SQL inside it. PL/SQL data types Each value in PL/SQL such as a constant, variable and parameter has a data type that determines the storage format, valid values, and allowed operations. PL/SQL has two kinds of data types: scalar and composite. The scalar types are types that store single values such as number, Boolean, character, and datetime whereas the composite types are types that store multiple values, for example, record and collection. PL/SQL divides the scalar data types into four families: • Number • Boolean • Character • Date time A scalar data type may have subtypes. A subtype is a data type that is a subset of another data type, which is its base type. A subtype further defines a base type by restricting the value or size of the base data type. Numeric data types The numeric data types represent real numbers, integers, and floating-point numbers. They are stored as NUMBER, IEEE floating-point storage types (BINARY_FLOAT and BINARY_DOUBLE), and PLS_INTEGER • The data types NUMBER, BINARY_FLOAT, and BINARY_DOUBLE are SQL data types. • The PLS_INTEGER datatype is specific to PL/SQL. It represents signed 32 bits integers that range from -2,147,483,648 to 2,147,483,647. • Because PLS_INTEGER datatype uses hardware arithmetic, they are faster than NUMBER operations, which uses software arithmetic.
  • 7. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page7 • In addition, PLS_INTEGER values require less storage than NUMBER. Hence, you should always use PLS_INTEGER values for all calculation in its range to increase the efficiency of programs. The PLS_INTEGER datatype has the following predefined subtypes: PLS_INTEGER subtypes Description NATURAL Represents nonnegative PLS_INTEGER values NATURALN Represents nonnegative PLS_INTEGER values with NOT NULL constraint POSITIVE Represents positive PLS_INTEGER values POSITIVEN Represents positive PLS_INTEGER value with NOT NULL constraint SIGNTYPE Represents three values -1, 0, or 1, which are useful for tri-state logic programming SIMPLE_INTEGER Represents PLS_INTEGER values with NOT NULL constraint. Boolean data type The BOOLEAN datatype has three data values: TRUE, FALSE, and NULL. Boolean values are typically used in control flow structure such as IF-THEN, CASE, and loop statements like LOOP, FOR LOOP, and WHILE LOOP. SQL does not have the BOOLEAN data type, therefore, you cannot: • Assign a BOOLEAN value to a table column. • Select the value from a table column into a BOOLEAN variable. • Use a BOOLEAN value in a SQL function. • Use a BOOLEAN expression in a SQL statement. • Use a BOOLEAN value in the DBMS_OUTPUT.PUTLINE and DBMS_OUTPUT.PUT subprograms.
  • 8. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page8 Character data types The character data types represent alphanumeric text. PL/SQL uses the SQL character data types such as CHAR, VARCHAR2, LONG, RAW, LONG RAW, ROWID, and UROWID. • CHAR(n) is a fixed-length character type whose length is from 1 to 32,767 bytes. • VARCHAR2(n) is varying length character data from 1 to 32,767 bytes. Datetime data types The datetime data types represent dates, timestamp with or without time zone and intervals. PL/SQL datetime data types are DATE, TIMESTAMP, TIMESTAMP WITH TIME ZONE, TIMESTAMP WITH LOCAL TIME ZONE, INTERVAL YEAR TO MONTH, and INTERVAL DAY TO SECOND. Data type synonyms Data types have synonyms for compatibility with non-Oracle data sources such as IBM Db2, SQL Server. And it is not a good practice to use data type synonym unless you are accessing a non-Oracle Database. Data Type Synonyms NUMBER DEC, DECIMAL, DOUBLE PRECISION, FLOAT, INTEGER, INT, NUMERIC, REAL, SMALLINT CHAR CHARACTER, STRING VARCHAR2VARCHAR PL/SQL Variables In PL/SQL, a variable is named storage location that stores a value of a particular data type. The value of the variable changes through the program. Before using a variable, you must declare it in the declaration section of a block. Declaring variables
  • 9. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page9 The syntax for a variable declaration is as follows: variable_name datatype [NOT NULL] [:= initial_value]; In this syntax: • First, specify the name of the variable. The name of the variable should be as descriptive as possible, e.g., l_total_sales, l_credit_limit, and l_sales_revenue. • Second, choose an appropriate data type for the variable, depending on the kind of value which you want to store, for example, number, character, Boolean, and datetime. By convention, local variable names should start with l_ and global variable names should have a prefix of g_ . The following example declares three variables l_total_sales, l_credit_limit, and l_contact_name: DECLARE l_total_sales NUMBER(15,2); l_credit_limit NUMBER (10,0); l_contact_name VARCHAR2(255); BEGIN NULL; END; Default values PL/SQL allows you to set a default value for a variable at the declaration time. To assign a default value to a variable, you use the assignment operator (:=) or the DEFAULT keyword. The following example declares a variable named l_product_name with an initial value 'Laptop': DECLARE l_product_name VARCHAR2( 100 ) := 'Laptop'; BEGIN NULL; END;
  • 10. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page10 It is equivalent to the following block: DECLARE l_product_name VARCHAR2(100) DEFAULT 'Laptop'; BEGIN NULL; END; In this example, instead of using the assignment operator := , we used the DEFAULT keyword to initialize a variable. NOT NULL constraint If you impose the NOT NULL constraint on a value, then the variable cannot accept a NULL value. Besides, a variable declared with the NOT NULL must be initialized with a non-null value. Note that PL/SQL treats a zero-length string as a NULL value. The following example first declares a variable named l_shipping_status with the NOT NULL constraint. Then, it assigns the variable a zero-length string. DECLARE l_shipping_status VARCHAR2( 25 ) NOT NULL := 'Shipped'; BEGIN l_shipping_status := ''; END; PL/SQL issued the following error: ORA-06502: PL/SQL: numeric or value error Because the variable l_shipping_status declared with the NOT NULL constraint, it could not accept a NULL value or zero-length string in this case. Variable assignments To assign a value to a variable, you use the assignment operator (:=), for example: DECLARE l_customer_group VARCHAR2(100) := 'Silver'; BEGIN l_customer_group := 'Gold';
  • 11. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page11 DBMS_OUTPUT.PUT_LINE(l_customer_group); END; You can assign a value of a variable to another as shown in the following example: DECLARE l_business_parter VARCHAR2(100) := 'Distributor'; l_lead_for VARCHAR2(100); BEGIN l_lead_for := l_business_parter; DBMS_OUTPUT.PUT_LINE(l_lead_for); END; Manipulating Data in PL/SQL Data Manipulation Language commands to exercise data operations in the database. Data operations can be populating the database tables with the application or business data, modifying the data and removing the data from the database, whenever required. Besides the data operations, there are set of commands which are used to control these operations DML stands for Data Manipulation Language. These statements are mainly used to perform the manipulation activity. It deals with the below operations. • Data Insertion • Data Update • Data Deletion • Data Selection In PL/SQL, we can do the data manipulation only by using the SQL commands. Data Insertion In PL/SQL, we can insert the data into any table using the SQL command INSERT INTO. This command will take the table name, table column and column values as the input and insert the value in the base table.
  • 12. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page12 The INSERT command can also take the values directly from another table using 'SELECT' statement rather than giving the values for each column. Through 'SELECT' statement, we can insert as many rows as the base table contains. Syntax: BEGIN INSERT INTO <table_name>(<column1 >,<column2>,...<column_n>) VALUES(<valuel><value2>,...:<value_n>); END; The above syntax shows the INSERT INTO command. The table name and values are a mandatory fields, whereas column names are not mandatory if the insert statements have values for all the column of the table. The keyword 'VALUES' is mandatory if the values are given separately as shown above. Syntax: BEGIN INSERT INTO <table_name>(<columnl>,<column2>,...,<column_n>) SELECT <columnl>,<column2>,.. <column_n> FROM <table_name2>; END; The above syntax shows the INSERT INTO command that takes the values directly from the <table_name2> using the SELECT command. The keyword 'VALUES' should not be present in this case as the values are not given separately. Data Update
  • 13. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page13 Data update simply means an update of the value of any column in the table. This can be done using 'UPDATE' statement. This statement takes the table name, column name and value as the input and updates the data. Syntax: BEGIN UPDATE <table_name> SET <columnl>=<VALUE1>,<column2>=<value2>,<column_n>=<value_n> WHERE <condition that uniquely identifies the record that needs to be update>; END; The above syntax shows the UPDATE. The keyword 'SET' instruct that PL/SQL engine to update the value of the column with the value given. 'WHERE' clause is optional. If this clause is not given, then the value of the mentioned column in the entire table will be updated. Data Deletion Data deletion means to delete one full record from the database table. The 'DELETE' command is used for this purpose. Syntax: BEGIN DELETE FROM <table_name>
  • 14. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page14 WHERE <condition that uniquely identifies the record that needs to be update>; END; The above syntax shows the DELETE command. The keyword 'FROM' is optional and with or without 'FROM' clause the command behaves in the same way. 'WHERE' clause is optional. If this clause is not given, then the entire table will be deleted. Data Selection Data projection/fetching means to retrieve the required data from the database table. This can be achieved by using the command 'SELECT' with 'INTO' clause. The 'SELECT' command will fetch the values from the database, and 'INTO' clause will assign these values to the local variable of the PL/SQL block. Below are the points that need to be considered in 'SELECT' statement. • 'SELECT' statement should return only one record while using 'INTO' clause as one variable can hold only one value. If the 'SELECT' statement returns more than one value than 'TOO_MANY_ROWS' exception will be raised. • 'SELECT' statement will assign the value to the variable in the 'INTO' clause, so it needs to get at least one record from the table to populate the value. If it didn't get any record, then the exception 'NO_DATA_FOUND' is raised. • The number of columns and their datatype in 'SELECT' clause should match with the number of variables and their datatypes in the 'INTO' clause. • The values are fetched and populated in the same order as mentioned in the statement. • 'WHERE' clause is optional that allows to having more restriction on the records that are going to be fetched. • 'SELECT' statement can be used in the 'WHERE' condition of other DML statements to define the values of the conditions. • The 'SELECT' statement when using 'INSERT', 'UPDATE', 'DELETE' statements should not have 'INTO' clause as it will not populate any variable in these cases. Syntax:
  • 15. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page15 BEGIN SELECT <columnl>,..<column_n> INTO <vanable 1 >,. .<variable_n> FROM <table_name> WHERE <condition to fetch the required records>; END; The above syntax shows the SELECT-INTO command. The keyword 'FROM' is mandatory that identifies the table name from which the data needs to be fetched. 'WHERE' clause is optional. If this clause is not given, then the data from the entire table will be fetched. Example 1: In this example, we are going to see how to perform DML operations in PL/SQL. We are going to insert the below four records into emp table. EMP_NAME EMP_NO SALARY MANAGER BBB 1000 25000 AAA XXX 1001 10000 BBB YYY 1002 10000 BBB ZZZ 1003 7500 BBB Then we are going to update the salary of 'XXX' to 15000, and we are going to delete the employee record 'ZZZ'. Finally, we are going to project the details of the employee 'XXX'. DECLARE l_emp_name VARCHAR2(250); l_emp_no NUMBER;
  • 16. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page16 l_salary NUMBER; l_manager VARCHAR2(250); BEGIN //Data Insert INSERT INTO emp(emp_name,emp_no,salary,manager) VALUES(‘BBB’,1000,25000,’AAA’); INSERT INTO emp(emp_name,emp_no,salary,manager) VALUES('XXX',1001,10000,’BBB); INSERT INTO emp(emp_name,emp_no,salary,managed VALUES(‘YYY',1002,10000,'BBB'); INSERT INTO emp(emp_name,emp_no,salary,manager) VALUES(‘ZZZ',1003,7500,'BBB'): COMMIT; // TCL Command Dbms_output.put_line(‘Values Inserted'); //Data Update and Delete UPDATE EMP SET salary=15000 WHERE emp_name='XXX'; COMMIT; Dbms_output.put_line(‘Values Updated'); DELETE emp WHERE emp_name='ZZZ'; COMMIT: Dbms_output.put_line('Values Deleted );
  • 17. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page17 //Display Statement SELECT emp_name,emp_no,salary,manager INTO l_emp_name,l_emp_no,l_salary,l_manager FROM emp WHERE emp_name='XXX'; Dbms_output.put line(‘Employee Detail’); Dbms_output.put line(‘----------------------’); Dbms_output.put_line(‘Employee Name:‘||l_emp_name); Dbms_output.put_line(‘Employee Number:‘||l_emp_no); Dbms_output.put_line (‘Employee Salary:‘||l_salary); Dbms output.put line(‘Emplovee Manager Name:‘||l_manager): END; / Output: Values Inserted Values Updated Values Deleted Employee Detail --------------------- Employee Name:XXX Employee Number:1001 Employee Salary:15000 Employee Manager Name:BBB
  • 18. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page18 SQL>select * from EMP; EMP_NAME EMP_NO SALARY MANAGER BBB 1000 25000 AAA BBB’ ,1000, 25000,’ AAA’ XXX 1001 15000 BBB YYY 1002 10000 BBB PL/SQL Procedures PL/SQL procedures create using CREATE PROCEDURE statement. The major difference between PL/SQL function or procedure, function return always value whereas procedure may or may not return value. When you create a function or procedure, you have to define IN/OUT/INOUT parameters parameters. • IN: IN parameter referring to the procedure or function and allow to overwritten the value of parameter. • OUT: OUT parameter referring to the procedure or function and allow to overwritten the value of parameter. • IN OUT: Both IN OUT parameter referring to the procedure or function to pass both IN OUT parameter, modify/update by the function or procedure and also get returned. IN/OUT/INOUT parameters you define in procedure argument list that get returned back to a result. When you create the procedure default IN parameter is passed in argument list. It's means value is passed but not returned. Explicitly you have define OUT/IN OUT parameter in argument list.
  • 19. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page19 PL/SQL Procedure Syntax CREATE [OR REPLACE] PROCEDURE [SCHEMA..] procedure_name [ (parameter [,parameter]) ] IS [declaration_section variable declarations; constant declarations; ] BEGIN [executable_section PL/SQL execute/subprogram body ] [EXCEPTION] [exception_section PL/SQL Exception block ] END [procedure_name]; / PL/SQL Procedure Example In this example we are creating a procedure to pass employee number argument and get that employee information from table. We have emp1 table having employee information,
  • 20. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page20 EMP_NO EMP_NAME EMP_DEPT EMP_SALARY 1 Forbs ross Web Developer 45k 2 marks jems Program Developer 38k 3 Saulin Program Developer 34k 4 Zenia Sroll Web Developer 42k Create PROCEDURE In this example passing IN parameter (no) and inside procedure SELECT ... INTO statement to get the employee information. pro1.sql SQL>dit pro1 CREATE or REPLACE PROCEDURE pro1(no in number,temp out emp1%rowtype) IS BEGIN SELECT * INTO temp FROM emp1 WHERE eno = no; END; / Execute PROCEDURE After write the PL/SQL Procedure you need to execute the procedure. SQL>@pro1 Procedure created. PL/SQL procedure successfully completed.
  • 21. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page21 PL/SQL Program to Calling Procedure This program (pro) call the above define procedure with pass employee number and get that employee information. pro.sql SQL>edit pro DECLARE temp emp1%rowtype; no number :=&no; BEGIN pro1(no,temp); dbms_output.put_line(temp.eno||' '|| temp.ename||' '|| temp.edept||' '|| temp.esalary||' '||); END; / SQL>@pro no number &n=2 2 marks jems Program Developer 38K PL/SQL procedure successfully completed. PL/SQL Drop Procedure You can drop PL/SQL procedure using DROP PROCEDURE statement,
  • 22. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page22 Syntax DROP PROCEDURE procedure_name; Example SQL>DROP PROCEDURE pro1; Procedure dropped. PL/SQL Functions PL/SQL functions block create using CREATE FUNCTION statement. The major difference between PL/SQL function or procedure, function return always value where as procedure may or may not return value. When you create a function or procedure, you have to define IN/OUT/INOUT parameters parameters. • IN: IN parameter referring to the procedure or function and allow to overwritten the value of parameter. • OUT: OUT parameter referring to the procedure or function and allow to overwritten the value of parameter. • IN OUT: Both IN OUT parameter referring to the procedure or function to pass both IN OUT parameter, modify/update by the function or procedure and also get returned. IN/OUT/INOUT parameters you define in function argument list that get returned back to a result. When you create the function default IN parameter is passed in argument list. It's means value is passed but not returned. Explicitly you have define OUT/IN OUT parameter in argument list. PL/SQL Functions Syntax CREATE [OR REPLACE] FUNCTION [SCHEMA..] function_name [ (parameter [,parameter]) ] RETURN return_datatype
  • 23. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page23 IS | AS [declaration_section variable declarations; constant declarations; ] BEGIN [executable_section PL/SQL execute/subprogram body ] [EXCEPTION] [exception_section PL/SQL Exception block ] END [function_name]; / PL/SQL Function Example EMP_NO EMP_NAME EMP_DEPT EMP_SALARY 1 Forbs ross Web Developer 45k 2 marks jems Program Developer 38k 3 Saulin Program Developer 34k
  • 24. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page24 In this example we are creating a function to pass employee number and get that employee name from table. We have emp1 table having employee information, Create Function So lets start passing IN parameter (no). Return datatype set varchar2. Now inside function SELECT ... INTO statement to get the employee name. fun1.sql SQL>edit fun1 CREATE or REPLACE FUNCTION fun1(no in number) RETURN varchar2 IS name varchar2(20); BEGIN select ename into name from emp1 where eno = no; return name; END; / Execute Function After write the PL/SQL function you need to execute the function. SQL>@fun1 Function created. PL/SQL procedure successfully completed. PL/SQL Program to Calling Function 4 Zenia Sroll Web Developer 42k
  • 25. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page25 This program call the above define function with pass employee number and get that employee name. fun.sql SQL>edit fun DECLARE no number :=&no; name varchar2(20); BEGIN name := fun1(no); dbms_output.put_line('Name:'||' '||name); end; / Result SQL>@fun no number &n=2 Name: marks jems PL/SQL procedure successfully completed. PL/SQL Drop Function You can drop PL/SQL function using DROP FUNCTION statements. Syntax DROP FUNCTION function_name; Example
  • 26. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page26 SQL>DROP FUNCTION fun1; Function dropped. PL/SQL Triggers Trigger automatically associated with DML statement, when DML statement execute trigger implicitly execute.You can create trigger using the CREATE TRIGGER statement. Component of Trigger • Triggering SQL statement: SQL DML (INSERT, UPDATE and DELETE) statement that execute and implicitly called trigger to execute. • Trigger Action: When the triggering SQL statement is execute, trigger automatically call and PL/SQL trigger block execute. • Trigger Restriction: We can specify the condition inside trigger to when trigger is fire. Type of Triggers • BEFORE Trigger: o BEFORE trigger execute before the triggering DML statement (INSERT, UPDATE, DELETE) execute. Triggering SQL statement is may or may not execute, depending on the BEFORE trigger conditions block. • AFTER Trigger: o AFTER trigger execute after the triggering DML statement (INSERT, UPDATE, DELETE) executed. Triggering SQL statement is execute as soon as followed by the code of trigger before performing Database operation. • ROW Trigger: o ROW trigger fire for each and every record which are performing INSERT, UPDATE, DELETE from the database table. If row deleting is define as trigger event, when trigger file, deletes the five rows each times from the table. • Statement Trigger:
  • 27. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page27 o Statement trigger fire only once for each statement. If row deleting is define as trigger event, when trigger file, deletes the five rows at once from the table. PL/SQL Triggers Syntax PL/SQL trigger define using CREATE TRIGGER statement. CREATE [OR REPLACE] TRIGGER trigger_name BEFORE | AFTER [INSERT, UPDATE, DELETE [COLUMN NAME..] ON table_name Referencing [ OLD AS OLD | NEW AS NEW ] FOR EACH ROW | FOR EACH STATEMENT [ WHEN Condition ] DECLARE [declaration_section variable declarations; constant declarations; ] BEGIN [executable_section PL/SQL execute/subprogram body ] EXCEPTION [exception_section PL/SQL Exception block ]
  • 28. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page28 END; Syntax Description o CREATE [OR REPLACE] TRIGGER trigger_name: Create a trigger with the given name. If already have overwrite the existing trigger with defined same name. o BEFORE | AFTER : Indicates when the trigger get fire. BEFORE trigger execute before when statement execute before. AFTER trigger execute after the statement execute. o [INSERT, UPDATE, DELETE [COLUMN NAME..]: Determines the performing trigger event. You can define more then one triggering event separated by OR keyword. o ON table_name: Define the table name to performing trigger event. o Referencing [ OLD AS OLD | NEW AS NEW ]: Give referencing to a old and new values of the data. :old means use existing row to perform event and :new means use executing new row to perform event. You can set referencing names user define name from old (or new). You can't referencing old values when inserting a record, or new values when deleting a record, because It's does not exist. o FOR EACH ROW | FOR EACH STATEMENT: Trigger must fire when each row gets Affected (ROW Trigger). and fire only once when the entire sql statement is execute (STATEMENT Trigger). o WHEN Condition: Optional. Use only for row level trigger. Trigger fire when specified condition is satisfy. PL/SQL Triggers Example You can make your own trigger using trigger syntax referencing. Here are fewer trigger example. Inserting Trigger This trigger execute BEFORE to convert ename field lowercase to uppercase. CREATE or REPLACE TRIGGER trg1 BEFORE
  • 29. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page29 INSERT ON emp1 FOR EACH ROW BEGIN :new.ename := upper(:new.ename); END; / Restriction to Deleting Trigger This trigger is preventing to deleting row. Delete Trigger Example CREATE or REPLACE TRIGGER trg1 AFTER DELETE ON emp1 FOR EACH ROW BEGIN IF :old.eno = 1 THEN raise_application_error(-2019, 'You can't delete this row'); END IF; END; / Delete Trigger Result SQL>delete from emp1 where eno = 1; Error Code: 2019 Error Name: You can't delete this row
  • 30. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page30 PL/SQL Packages PL/SQL Packages is schema object and collection of related data type (variables, constants), cursors, procedures, functions are defining within a single context. Package are divide into two part, • Package Specification • Package Body Package specification block you can define variables, constants, exceptions and package body you can create procedure, function, subprogram. PL/SQL Package Advantages • You can create package to store all related functions and procedures are grouped together into single unit called packages. • Package are reliable to granting a privileges. • All function and procedure within a package can share variable among them. • Package are support overloading to overload functions and procedures. • Package are improve the performance to loading the multiple object into memory at once, therefore, subsequent calls to related program doesn't required to calling physically I/O. • Package are reduce the traffic because all block execute all at once. PL/SQL Specification: This contain the list of variables, constants, functions, procedure names which are the part of the package. PL/SQL specification are public declaration and visible to a program. Defining Package Specification Syntax CREATE [OR REPLACE] PACKAGE package_name IS | AS
  • 31. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page31 [variable_declaration ...] [constant_declaration ...] [exception_declaration ...] [cursor_specification ...] [PROCEDURE [Schema..] procedure_name [ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ] ] [FUNCTION [Schema..] function_name [ (parameter {IN,OUT,IN OUT} datatype [,parameter]) ] RETURN return_datatype ] END [package_name]; PL/SQL Body: This contains the actual PL/SQL statement code implementing the logics of functions, procedures which are you already before declare in "Package specification". Creating Package Body Syntax CREATE [OR REPLACE] PACKAGE BODY package_name IS | AS [private_variable_declaration ...] [private_constant_declaration ...] BEGIN [initialization_statement] [PROCEDURE [Schema..] procedure_name
  • 32. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page32 [ (parameter [,parameter]) ] IS | AS variable declarations; constant declarations; BEGIN statement(s); EXCEPTION WHEN ... END ] [FUNCTION [Schema..] function_name [ (parameter [,parameter]) ] RETURN return_datatype IS | AS variable declarations; constant declarations; BEGIN statement(s); EXCEPTION WHEN ... END ] [EXCEPTION
  • 33. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page33 WHEN built-in_exception_name_1 THEN User defined statement (action) will be taken; ] END; / PL/SQL Package Example PL/SQL Package example step by step explain to you, you are create your own package using this reference example. We have emp1 table having employee information, EMP_NO EMP_NAME EMP_DEPT EMP_SALARY 1 Forbs ross Web Developer 45k 2 marks jems Program Developer 38k 3 Saulin Program Developer 34k 4 Zenia Sroll Web Developer 42k Package Specification Create Package specification code for defining procedure, function IN or OUT parameter and execute package specification program. CREATE or REPLACE PACKAGE pkg1 IS | AS PROCEDURE pro1 (no in number, name out varchar2);
  • 34. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page34 FUNCTION fun1 (no in number) RETURN varchar2; END; / Package Body Create Package body code for implementing procedure or function that are defined package specification. Once you implement execute this program. CREATE or REPLACE PACKAGE BODY pkg1 IS PROCEDURE pro1(no in number,info our varchar2) IS BEGIN SELECT * INTO temp FROM emp1 WHERE eno = no; END; FUNCTION fun1(no in number) return varchar2 IS name varchar2(20); BEGIN SELECT ename INTO name FROM emp1 WHERE eno = no; RETURN name; END;
  • 35. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page35 END; / Pl/SQL Program calling Package Now we have a one package pkg1, to call package defined function, procedures also pass the parameter and get the return result. pkg_prg.sql DECLARE no number := &no; name varchar2(20); BEGIN pkg1.pro1(no,info); dbms_output.put_line('Procedure Result'); dbms_output.put_line(info.eno||' '|| info.ename||' '|| info.edept||' '|| info.esalary||' '||); dbms_output.put_line('Function Result'); name := pkg1.fun1(no); dbms_output.put_line(name); END;
  • 36. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page36 / Result Now execute the above created pkg_prg.sql program to asking which user information you want to get, you put user id and give information. SQL>@pkg_prg no number &n=2 Procedure Result 2 marks jems Program Developer 38K Function Result marks jems PL/SQL procedure successfully completed. PL/SQL Exception Handling • PL/SQL exceptions are predefined and raised automatically into oracle engine when any error occur during a program. • Each and every error has defined a unique number and message. When warning/error occur in program it's called an exception to contains information about the error. • In PL/SQL built in exceptions or you make user define exception. Examples of built- in type (internally) defined exceptions division by zero, out of memory. Some common built-in exceptions have predefined names such as ZERO_DIVIDE and STORAGE_ERROR. • Normally when exception is fire, execution stops and control transfers to the exception-handling part of your PL/SQL block. Internal exceptions are raised implicitly (automatically) by the run-time system. User-defined exceptions must be raised explicitly by RAISE statements, which are also raise predefined exceptions. PL/SQL exceptions consist following three, • Exception Type • Error Code • Error Message
  • 37. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page37 Syntax DECLARE declaration statement(s); BEGIN statement(s); EXCEPTION WHEN built-in_exception_name_1 THEN User defined statement (action) will be taken; WHEN built-in_exception_name_2 THEN User defined statement (action) will be taken; END; Example builtin_exp.sql SQL>edit buitin_exp DECLARE temp enum%rowtype; BEGIN SELECT * INTO temp FROM enum WHERE eno=3; EXCEPTION WHEN no_data_found THEN dbms_output.put_line("Table haven't data"); END; /
  • 38. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page38 Result SQL>@buitin_exp Table haven't data PL/SQL procedure successfully operation. PL/SQL User Defined Exception PL/SQL user defined exception to make your own exception. PL/SQL give you control to make your own exception base on oracle rules. User define exception must be declare yourself and RAISE statement to raise explicitly. How to Define Exception Declare exception You must have to declare user define exception name in DECLARE block. user_define_exception_name EXCEPTION; Exception and Variable both are same way declaring but exception use for store error condition not a storage item. RAISE exception RAISE statement to raised defined exception name and control transfer to a EXCEPTION block. RAISE user_define_exception_name; Implement exception condition In PL/SQL EXCEPTION block add WHEN condition to implement user define action. WHEN user_define_exception_name THEN User defined statement (action) will be taken; Syntax
  • 39. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page39 Check this user defined exception syntax, DECLARE user_define_exception_name EXCEPTION; BEGIN statement(s); IF condition THEN RAISE user_define_exception_name; END IF; EXCEPTION WHEN user_define_exception_name THEN User defined statement (action) will be taken; END; Example user_exp.sql SQL>edit user_exp DECLARE myex EXCEPTION; i NUMBER; BEGIN FOR i IN (SELECT * FROM enum) LOOP IF i.eno = 3 THEN RAISE myex; END IF;
  • 40. D.GAYA, Assistant Professor, Department of Computer Science, PUCC. Page40 END LOOP; EXCEPTION WHEN myex THEN dbms_output.put.line('Employee number already exist in enum table.'); END; / Result SQL>@user_exp Employee number already exist in enum table.