DMS Final CH 4
DMS Final CH 4
PL/SQL PROGRAMMING
PL/SQL is a combination of SQL along with the procedural features of programming languages. It was
developed by Oracle Corporation in the early 90's to enhance the capabilities of SQL.
Advantages of PL/SQL
Declarations
1 This section starts with the keyword DECLARE. It is an optional section and defines
all variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory
2
section. It consists of the executable PL/SQL statements of the program. It should
have at least one executable line of code.
Exception Handling
3 This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program.
Data type
State any four PL/SQL data types. [S 19]
The PL/SQL variables, constants and parameters must have a valid data type, which specifies a
storage format, constraints, and a valid range of values.
Scalar
1 Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.
Composite
2 Data items that have internal components that can be accessed individually.
For example, collections and records.
Reference
3
Pointers to other data items.
1 Numeric
Numeric values on which arithmetic operations are performed.
2 Character
Alphanumeric values that represent single characters or strings of characters.
3 Boolean
Logical values on which logical operations are performed.
4 Datetime
Dates and times.
Variable
A variable is nothing but a name given to a storage area that our programs can manipulate.
Each variable in PL/SQL has a specific data type, which determines the size and the layout of
the variable's memory; the range of values that can be stored within that memory and the set
of operations that can be applied to the variable.
The name of a PL/SQL variable consists of a letter optionally followed by more letters,
numerals, dollar signs, underscores, and number signs and should not exceed 30
characters. By default, variable names are not case-sensitive. You cannot use a reserved
PL/SQL keyword as a variable name.
Syntax −
variable_name datatype [:=initial_value] ;
Example:
salary number(8);
Declaring a Constant
A constant is declared using the CONSTANT keyword. It requires an initial value and does not
allow that value to be changed. For example −
PI CONSTANT NUMBER := 3.141592654;
CONTROL STRUCTURES
Q] Explain any one control structure in PL/SQL with example.
PL/SQL has three categories of control statements: conditional control statements, loop
statements and sequential control statements.
1. IF statement
It is the simplest form of the IF control statement, frequently used in decision-making and
changing the control flow of the program execution.
The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if the
condition is FALSE or NULL, then the IF statement does nothing.
Syntax
IF condition
THEN
Statement;
END IF;
Where condition is a Boolean or relational condition and S is a simple or compound statement.
Following is an example of the IF-THEN statement −
IF (a <= 20) THEN
c:= c+1;
END IF;
If the Boolean expression condition evaluates to true, then the block of code inside the if
statement will be executed.
If the Boolean expression evaluates to false, then the first set of code after the end of the if
statement (after the closing end if) will be executed.
DECLARE
a number(2) := 10;
BEGIN
a:= 10;
IF( a < 20 ) THEN
2. IF-THEN-ELSE
A sequence of IF-THEN statements can be followed by an optional sequence
of ELSE statements, which execute when the condition is FALSE.
Syntax
IF condition THEN
S1;
ELSE
S2;
END IF;
Where, S1 and S2 are different sequence of statements. In the IF-THEN-ELSE
statements, when the test condition is TRUE, the statement S1 is executed and S2 is
skipped; when the test condition is FALSE, then S1 is bypassed and statement S2 is
executed.
Example
Let us try an example that will help you understand the concept −
DECLARE
a number(3) := 100;
BEGIN
IF-THEN-ELSIF
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF...ELSE statement.
The ELSIF clause lets you add additional conditions.
When using IF-THEN-ELSIF statements there are a few points to keep in mind.
It's ELSIF, not ELSEIF.
An IF-THEN statement can have zero or one ELSE's and it must come after any
ELSIF's.
An IF-THEN statement can have zero to many ELSIF's and they must come before
the ELSE.
Once an ELSIF succeeds, none of the remaining ELSIF's or ELSE's will be tested.
Syntax
The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
Example
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 ) THEN
dbms_output.put_line('Value of a is 10' );
ELSIF ( a = 20 ) THEN
dbms_output.put_line('Value of a is 20' );
ELSIF ( a = 30 ) THEN
dbms_output.put_line('Value of a is 30' );
ELSE
dbms_output.put_line('None of the values is matching');
END IF;
dbms_output.put_line('Exact value of a is: '|| a );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
None of the values is matching
Exact value of a is: 100
Nested IF-ELSE
It is always legal in PL/SQL programming to nest the IF-ELSE statements, which means
you can use one IF or ELSE IF statement inside another IF or ELSE IF statement(s).
Syntax
IF( boolean_expression 1)THEN
-- executes when the boolean expression 1 is true
IF(boolean_expression 2) THEN
-- executes when the boolean expression 2 is true
sequence-of-statements;
END IF;
ELSE
-- executes when the boolean expression 1 is not true
else-statements;
END IF;
Example
DECLARE
a number(3) := 100;
b number(3) := 200;
BEGIN
-- check the boolean condition
IF( a = 100 ) THEN
-- if condition is true then check the following
IF( b = 200 ) THEN
-- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200
CASE statement
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
Like the IF statement, the CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression, the value of which is used to select one of
several alternatives.
Syntax
The syntax for the case statement in PL/SQL is −
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Example
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Excellent
Syntax
The syntax for the searched case statement in PL/SQL is −
CASE
WHEN selector = 'value1' THEN S1;
WHEN selector = 'value2' THEN S2;
WHEN selector = 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Example
DECLARE
grade char(1) := 'B';
BEGIN
case
when grade = 'A' then dbms_output.put_line('Excellent');
when grade = 'B' then dbms_output.put_line('Very good');
when grade = 'C' then dbms_output.put_line('Well done');
when grade = 'D' then dbms_output.put_line('You passed');
when grade = 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
end case;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Very good
Basic loop structure encloses sequence of statements in between the LOOP and END
LOOP statements. With each iteration, the sequence of statements is executed and then control
resumes at the top of the loop.
Syntax
The syntax of a basic loop in PL/SQL programming language is −
LOOP
Sequence of statements;
END LOOP;
Here, the sequence of statement(s) may be a single statement or a block of statements. An EXIT
statement or an EXIT WHEN statement is required to break the loop.
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60
You can use the EXIT WHEN statement instead of the EXIT statement −
2. WHILE LOOP
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target
statement as long as a given condition is true.
Syntax
WHILE condition LOOP
sequence_of_statements
END LOOP;
Before each iteration of the loop, the condition is evaluated. If the condition is true, the
sequence of statements is executed, then control resumes at the top of the loop.
If the condition is false or null, the loop is bypassed and control passes to the next statement.
Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
3. FOR LOOP
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
A FOR LOOP is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times.
Syntax
FOR counter IN initial_value .. final_value LOOP
sequence_of_statements;
END LOOP;
Following is the flow of control in a For Loop −
The initial step is executed first, and only once. This step allows you to declare and
initialize any loop control variables.
Next, the condition, i.e., initial_value .. final_value is evaluated. If it is TRUE, the
body of the loop is executed. If it is FALSE, the body of the loop does not execute
and the flow of control jumps to the next statement just after the for loop.
After the body of the for loop executes, the value of the counter variable is increased
or decreased.
The condition is now evaluated again. If it is TRUE, the loop executes and the
process repeats itself (body of loop, then increment step, and then again condition).
After the condition becomes FALSE, the FOR-LOOP terminates.
Following are some special characteristics of PL/SQL for loop −
The initial_value and final_value of the loop variable or counter can be literals,
variables, or expressions but must evaluate to numbers. Otherwise, PL/SQL raises
the predefined exception VALUE_ERROR.
The initial_value need not be 1; however, the loop counter increment (or
decrement) must be 1.
PL/SQL allows the determination of the loop range dynamically at run time.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
value of a: 19
value of a: 20
EXIT statement
The EXIT statement in PL/SQL programming language has the following two usages −
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
When the EXIT statement is encountered inside a loop, the loop is immediately
terminated and the program control resumes at the next statement following the
loop.
If you are using nested loops (i.e., one loop inside another loop), the EXIT statement
will stop the execution of the innermost loop and start executing the next line of code
after the block.
Syntax
The syntax for an EXIT statement in PL/SQL is as follows −
EXIT;
Example
DECLARE
a number(2) := 10;
BEGIN
-- while loop execution
WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a > 15 THEN
-- terminate the loop using the exit statement
EXIT;
END IF;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Syntax
The syntax for an EXIT WHEN statement in PL/SQL is as follows −
EXIT WHEN condition;
The EXIT WHEN statement replaces a conditional statement like if-then used with the
EXIT statement.
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is:60
CONTINUE
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
The CONTINUE statement causes the loop to skip the remainder of its body and
immediately retest its condition prior to reiterating. In other words, it forces the next iteration
of the loop to take place, skipping any code in between.
Syntax
The syntax for a CONTINUE statement is as follows −
CONTINUE;
Example
DECLARE
a number(2) := 10;
BEGIN
-- while loop execution
WHILE a < 20 LOOP
a := a + 1;
IF a = 15 THEN
CONTINUE;
ELSE
dbms_output.put_line ('value of a: ' || a);
END IF;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
GOTO statement
Arrow Computer Academy Prof. Somwanshi A. A. (8788335443)
A GOTO statement in PL/SQL programming language provides an unconditional jump from
the GOTO to a labeled statement in the same subprogram.
NOTE − The use of GOTO statement is not recommended in any programming language
because it makes it difficult to trace the control flow of a program, making the program hard
to understand and hard to modify. Any program that uses a GOTO can be rewritten so that
it doesn't need the GOTO.
Syntax
The syntax for a GOTO statement in PL/SQL is as follows −
GOTO label;
..
..
<< label >>
statement;
Example
DECLARE
a number(2) := 10;
BEGIN
<<loopstart>>
-- while loop execution
WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 15 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Ans
DECLARE
num number:=#
fact number:=1;
BEGIN
while num!=0
loop
fact:=fact*num;
num:=num-1
end loop;
dbms_output.put_line(‘Factorial =’||fact);
END;
/
declare
n number;
i number;
rev number:=0;
r number;
begin
n:=&n;
while n>0
loop
r:=mod(n,10);
rev:=(rev*10)+r;
n:=trunc(n/10);
end loop;
dbms_output.put_line('reverse is '||rev);
end;
A] Procedure
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the
parameters. IN represents the value that will be passed from outside and OUT
represents the parameter that will be used to return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example
The following example creates a simple procedure that displays the string 'Hello World!' on
the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
When the above code is executed using the SQL prompt, it will produce the following result
−
Procedure created.
IN
1 An IN parameter lets you pass a value to the subprogram. It is a read-only
parameter. Inside the subprogram, an IN parameter acts like a constant. It cannot
be assigned a value.. It is the default mode of parameter passing.
OUT
2
An OUT parameter returns a value to the calling program. Inside the subprogram, an
OUT parameter acts like a variable. You can change its value .
IN OUT
3
An IN OUT parameter passes an initial value to a subprogram and returns an updated
value to the caller. It can be assigned a value and the value can be read.
Function
Function is a logically grouped set of SQL and Pl/SQL statements that perform a specific task. A
function is same as a procedure except that it returns a value.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement. The simplified
syntax for the CREATE OR REPLACE PROCEDURE statement is as follows −
Where,
function-name specifies the name of the function.
Example
The following example illustrates how to create and call a standalone function. This
function returns the total number of CUSTOMERS in the customers table.
We will use the CUSTOMERS table, which we have already created.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
CREATE OR REPLACE FUNCTION totalCustomers
RETURN number IS
total number(2) := 0;
BEGIN
SELECT count(*) into total
FROM customers;
RETURN total;
END;
/
When the above code is executed using the SQL prompt, it will produce the following result
−
Function created.
Calling a Function
While creating a function, you give a definition of what the function has to do. To use a
function, you will have to call that function to perform the defined task. When a program
calls a function, the program control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or
when the last end statement is reached, it returns the program control back to the main
program.
Example
The following example demonstrates Declaring, Defining, and Invoking a Simple PL/SQL
Function that computes and returns the maximum of two values.
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
c:= findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Maximum of (23,45): 45
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically generated and used by the system during the
manipulation of a DML query. Programmers cannot control the implicit cursors and the
information in it.
Whenever a DML statement (INSERT, UPDATE and DELETE) is issued, an implicit cursor is
associated with this statement. For INSERT operations, the cursor holds the data that needs to
be inserted. For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.
In PL/SQL, you can refer to the most recent implicit cursor as the SQL cursor, which always
has attributes such as %FOUND, %ISOPEN, %NOTFOUND, and %ROWCOUNT.
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or
more rows or a SELECT INTO statement returned one or more rows.
Otherwise, it returns FALSE.
%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or
DELETE statement affected no rows, or a SELECT INTO statement returned
no rows. Otherwise, it returns FALSE.
%ISOPEN
3
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
%ROWCOUNT
4
Returns the number of rows affected by an INSERT, UPDATE, or DELETE
statement, or returned by a SELECT INTO statement.
Example
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer by 500
and use the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
6 customers selected
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Declaring the cursor defines the cursor with a name and the associated SELECT statement. For
example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the
rows returned by the SQL statement into it. For example, we will open the above defined
cursor as follows −
OPEN c_customers;
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows
from the above-opened cursor as follows −
FETCH c_customers INTO c_id, c_name, c_addr;
Closing the cursor means releasing the allocated memory. For example, we will close the
above-opened cursor as follows −
CLOSE c_customers;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
Benefits of Triggers
Triggers can be written for the following purposes −
Creating Triggers
CREATE [OR REPLACE ] TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF col_name]
ON table_name
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;
Where,
CREATE [OR REPLACE] TRIGGER trigger_name − Creates or replaces an existing trigger with
the trigger_name.
{BEFORE | AFTER | INSTEAD OF} − This specifies when the trigger will be executed. The
INSTEAD OF clause is used for creating trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} − This specifies the DML operation.
[OF col_name] − This specifies the column name that will be updated.
[ON table_name] − This specifies the name of the table associated with the trigger.
Example
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire for
INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger
will display the salary difference between the old values and new values −
CREATE OR REPLACE TRIGGER display_salary_changes
BEFORE DELETE OR INSERT OR UPDATE
ON customers
FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff number;
BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' || :OLD.salary);
dbms_output.put_line('New salary: ' || :NEW.salary);
dbms_output.put_line('Salary difference: ' || sal_diff);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Trigger created.
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement,
which will create a new record in the table −
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, 'Kriti', 22, 'HP', 7500.00 );
To delete a trigger:
System-defined exceptions
User-defined exceptions
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exceptionn-handling-statements
END;
Note:
When other keyword should be used only at the end of the exception handling block as no
exception handling part present later will get executed as the control will exit from the block
after executing the WHEN OTHERS.
DECLARE
temp varchar(20);
BEGIN
SELECT g_id into temp from student where g_name='Arrow';
Exception
WHEN no_data_found THEN
dbms_output.put_line('ERROR there is no name as Arrow in student table');
end;
Output:
ERROR there is no name as Arrow in student table
DECLARE
a int:=10;
b int:=0;
answer int;
BEGIN
answer:=a/b;
dbms_output.put_line('the result after division is'||answer);
Exception
WHEN zero_divide THEN
dbms_output.put_line('dividing by zero please check the values again');
dbms_output.put_line('the value of a is '||a);
dbms_output.put_line('the value of b is '||b);
END;
Output:
dividing by zero please check the values again
the value of a is 10
the value of b is 0
A user defined exception must be declared and then raised explicitly by the programmer by
using the command RAISE.
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
Q] Write a PL/SQL program which accepts the customer_ID from the user. If the user
enters an invalid ID then the exception invalid_id is raised using exception handling.
DECLARE
customer_id number(10);
invalid_id Exception;
BEGIN
customer_id:=& customer_id;
if(customer_id <0) then
raise invalid_id;
end if;
EXCEPTION
WHEN invalid_id THEN
dbms_output.put_line(‘Id can not be negative’);
END;
Q] Write a PL/SQL program which accepts the age from the user. If the user enters an age
<18 then the exception invalid_age is raised using exception handling.
Declare
age number(3);
invalid_age Exception;
Begin
age:=&age;
if age<18 then
raise invalid_age;
end if;
Exception
when invalid_age then
dbms_output.put_line(“Age should be greater than or equal to 18”)
End
DECLARE
x int:=&x; /*taking value at run time*/
y int:=&y;
div_r float;
exp1 EXCEPTION;
exp2 EXCEPTION;
BEGIN
IF y=0 then
raise exp1;
ELSE
div_r:= x / y;
dbms_output.put_line('the result is '||div_r);
END IF;
EXCEPTION
WHEN exp1 THEN
dbms_output.put_line('Error');
dbms_output.put_line('division by zero not allowed');
Input 1:
x = 20
y = 10
Output: the result is 2
Input 2:
x = 20
y=0
Output:
Error
Input 3:
x=20
y = 30
Output:
Error
y is greater than x please check the input
Write a PL/SQL code to check whether specified employee is present in Emp table or not.
Accept empno from user. If employee does not exist display message using exception
handling.
declare
no emp.empno%type;
begin
no:=&no;
select empno into no from emp where empno=no;
dbms_output.put_line('Empno is present: '||no);
exception
when no_data_found then
dbms_output.put_line('Empno not present');
end;