0% found this document useful (0 votes)
12 views

Dbms Unit II Plsql Pnr 2 of 2

Uploaded by

abhinav boge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Dbms Unit II Plsql Pnr 2 of 2

Uploaded by

abhinav boge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

PL/SQL – PROCEDURES (IN ORACLE)

 CREATE [OR REPLACE] PROCEDURE


procedure_name [(parameter_name [IN | OUT |
IN OUT] type [, ...])] {AS}

Poonam Railkar, SKNCOE


 BEGIN < procedure_body >

 END procedure_name;

•procedure-name specifies the name of the procedure.


•[OR REPLACE] option allows modifying an existing procedure.
•The optional parameter list contains name, mode and types of the
parameters. IN represents that value will be passed from outside
and OUT represents that this parameter will be used to return a
value outside of the procedure.
•procedure-body contains the executable part.
 In MySQL, a parameter has one of three modes:
IN,OUT, or INOUT

Poonam Railkar, SKNCOE


 IN – is the default mode. When you define an IN
parameter in a stored procedure, the calling program
has to pass an argument to the stored procedure

 OUT – the value of an OUT parameter can be


changed inside the stored procedure and its new
value is passed back to the calling program.

 INOUT – an INOUT parameter is the combination of


IN and OUT parameters. It means that the calling
program may pass the argument, and the stored
procedure can modify the INOUT parameter and pass
the new value back to the calling program.
PARTS OF A PL/SQL SUBPROGRAM

 Each PL/SQL subprogram has a name, and may have a parameter list. Like
anonymous PL/SQL blocks and, the named blocks a subprograms will also
have following three parts:

Poonam Railkar, SKNCOE


S.N. Parts & Description

1 Declarative Part
It is an optional part. However, the declarative part for a subprogram does not start
with the DECLARE keyword. It contains declarations of types, cursors, constants,
variables, exceptions, and nested subprograms. These items are local to the
subprogram and cease to exist when the subprogram completes execution.
2 Executable Part
This is a mandatory part and contains statements that perform the designated
action.
3 Exception-handling
This is again an optional part. It contains the code that handles run-time errors.
stored procedure that selects offices located in a
particular country.
Mysql> DELIMITER //

Mysql>CREATE PROCEDURE GetOfficeByCountry(IN

Poonam Railkar, SKNCOE


countryName VARCHAR(255))
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //

Mysql> DELIMITER ;

Mysql> CALL GetOfficeByCountry('USA');


PROCEDURE 1 IN ORACLE
create or replace procedure proc1
(temp_id in student.sid%type,
temp_mark in stduent.marks%type)

Poonam Railkar, SKNCOE


as
begin
update student set marks = temp_mark where sid
= temp_id;
end;

execute proc1(&temp_id, &temp_mark);


LANGUAGE CONSTRUCTS FOR PROCEDURES & FUNCTIONS

 SQL supports constructs that gives it almost all the power of a


general-purpose programming language.
 Compound statement: begin … end,
 May contain multiple SQL statements between begin and end.
 Local variables can be declared within a compound statements

 While and repeat statements:


 while boolean expression do
sequence of statements ;
end while
 repeat
sequence of statements ;
until boolean expression
end repeat
➢ DELIMITER $$ ➢ DELIMITER $$
➢ DROP PROCEDURE IF EXISTS ➢ DROP PROCEDURE IF EXISTS
test_mysql_while_loop$$ mysql_test_repeat_loop$$

➢ CREATE PROCEDURE ➢ CREATE PROCEDURE


test_mysql_while_loop() mysql_test_repeat_loop()
BEGIN
BEGIN
DECLARE x INT;
DECLARE x INT;
DECLARE str VARCHAR(255);
DECLARE str VARCHAR(255); SET x = 1;
SET x = 1; SET str = '';

Poonam Railkar, SKNCOE


SET str = ''; REPEAT
WHILE x <= 5 DO SET str = CONCAT(str, x, ',');
SET str = CONCAT(str, x, ','); SET x = x + 1;
SET x = x + 1; UNTIL x > 5
END WHILE; END REPEAT;
SELECT str; SELECT str;
END$$ END$$

➢ DELIMITER ; ➢ DELIMITER ;

mysql> call test_mysql_while_loop(); mysql> call mysql_test_repeat_loop() ;


+------------+ +------------+
| str | | str |
+------------+ +------------+
| 1,2,3,4,5, | | 1,2,3,4,5, |
+------------+ +------------+
1 row in set (0.03 sec) 1 row in set (0.02 sec)
LOOP
CREATE PROCEDURE doiterate(p1 INT)
BEGIN Syntax of the LOOP statement
label1: LOOP with LEAVE statement :
SET p1 = p1 + 1;
IF p1 < 10 THEN ITERATE label1; [labelname]: LOOP
END IF; -- terminate the loop
LEAVE label1; IF condition THEN

Poonam Railkar, SKNCOE


END LOOP label1; LEAVE [labelname];
SET @x = p1; END IF;
END; END LOOP;

mysql> select @x;


| @x |
+------+
| NULL |
+------+
mysql> call doiterate(1);
Query OK, 0 rows affected (0.06 sec)
mysql> select @x;
+------+
| @x |
+------+
| 10 |
+------+
CREATE PROCEDURE firstcaseprocedure(variable
varchar(10))
BEGIN

Poonam Railkar, SKNCOE


CASE variable
WHEN 'first' THEN select 'First condition executed';
WHEN 'second' THEN select 'Second condition
executed';
WHEN 'third' THEN select 'Third condition
executed';
ELSE select 'Else condition executed';
END CASE;
END;
FUNCTIONS

A PL/SQL function is same as a procedure except that it returns a value.

Creating a Function

CREATE [OR REPLACE] FUNCTION function_name


[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype

Poonam Railkar, SKNCOE


{IS}
BEGIN
< function_body >
Return variable;
END [function_name];

My sql:
CREATE FUNCTION function_name
[[IN | OUT | IN OUT] parameter_name type [, ...])]
RETURNS return_datatype
BEGIN
< function_body >
Return variable;
END;
Ex: Creating and calling a standalone function. This function returns the total
number of CUSTOMERS in the customers table

Select * from customers;


+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |

Poonam Railkar, SKNCOE


| 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;
To call a function you simply need to pass the required
parameters along with function name and if function returns a
value then you can store returned value.

DECLARE
c number(2);
BEGIN

Poonam Railkar, SKNCOE


c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;

When the above code is executed at SQL prompt, it produces the


following result:
Total no. of Customers: 6
Oracle
2: Function that computes and returns the maximum of two
values

DECLARE
a number;
b number;

Poonam Railkar, SKNCOE


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;

Poonam Railkar, SKNCOE


/
When the above code is executed at SQL prompt, it produces
the following result:

Maximum of (23,45): 45
PL/SQL procedure successfully completed.
Student_result(student_id, student_marks)Write procedure to display
grades for marks: less than 35 fail, less than 50 C grade less than 70 B
grade otherwise A grade

CREATE PROCEDURE passorfail(sid int)


BEGIN
DECLARE marks int;
select student_marks into marks from student_result where student_id = sid;
IF marks<35 THEN select 'Fail';

Poonam Railkar, SKNCOE


ELSEIF marks<50 THEN select 'C Grade';
ELSEIF marks<70 THEN select 'B Grade';
ELSE select 'A Grade';
END IF
END;
OR

CREATE PROCEDURE passorfail(sid int)


BEGIN
DECLARE marks int;
select student_marks into marks from student_result where student_id = sid;
CASE
WHEN marks<35 THEN select 'Fail';
WHEN marks<50 THEN select 'C Grade';
WHEN marks<70 THEN select 'B Grade';
ELSE select 'A Grade';
END CASE;
END;
TRIGGERS
Triggers are stored programs, which are automatically executed or
fired when some events occur. Triggers are in fact written to be
executed in response to any of the following events:

Poonam Railkar, SKNCOE


•A database manipulation (DML) statement (DELETE,
INSERT, or UPDATE).
•A database definition (DDL) statement (CREATE, ALTER,
or DROP).

•A trigger can be used to keep an audit trail of table(store modified


and deleted records of the table) along with operations and the time
on which the operation was performed

•It can be used to prevent invalid transactions


 .
 A SQL trigger is a special type of stored
procedure. It is special because it is not called
directly like a stored procedure. The main
difference between a trigger and a stored
procedure is that a trigger is called

Poonam Railkar, SKNCOE


automatically when a data modification event
is made against a table whereas a stored
procedure must be called explicitly.
The Syntax for creating a trigger is: In Oracle

CREATE [OR REPLACE ] TRIGGER trigger_name


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | DELETE [OR] | UPDATE [OF col_name]
}

Poonam Railkar, SKNCOE


ON table_name
[REFERENCING OLD AS d 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 replace
an existing trigger with the trigger_name.
{BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger
would be executed. The INSTEAD OF clause is used for creating trigger
on a view.
{INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML
operation.

Poonam Railkar, SKNCOE


[OF col_name]: This specifies the column name that would be updated.
[ON table_name]: This specifies the name of the table associated with
the trigger.
[REFERENCING OLD AS d NEW AS n]: This allows you to refer new
and old values for various DML statements, like INSERT, UPDATE,
and DELETE.
[FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger
would be executed for each row being affected. Otherwise the trigger will
execute just once when the SQL statement is executed, which is called a
table level trigger (statement level trigger).
WHEN (condition): This provides a condition for rows for which the
trigger would fire. This clause is valid only for row level triggers.
MySQL triggers
In MySQL, a trigger is a set of SQL statements that is invoked
automatically when a change is made to the data on the associated
table. A trigger can be defined to be invoked either before or after the
data is changed by INSERT, UPDATE or DELETE statement. Before
MySQL version 5.7.2, you can to define maximum six triggers for each

Poonam Railkar, SKNCOE


table.

•BEFORE INSERT – activated before data is inserted into the table.


•AFTER INSERT – activated after data is inserted into the table.
•BEFORE UPDATE – activated before data in the table is updated.
•AFTER UPDATE – activated after data in the table is updated.
•BEFORE DELETE – activated before data is removed from the table.
•AFTER DELETE – activated after data is removed from the table.

•When you use a statement that does not use INSERT, DELETE or
UPDATE statement to change data in a table, the triggers
associated with the table are not invoked. For example, the
TRUNCATE statement removes all data of a table but does
not invoke the trigger associated with that table.
MYSQL TRIGGER SYNTAX
 CREATE TRIGGER trigger_name trigger_time
trigger_event
 ON table_name
 FOR EACH ROW
 BEGIN

Poonam Railkar, SKNCOE


 ...
 END;

OR

DELIMITER $$
CREATE TRIGGER trigger_name
[BEFORE|AFTER] [INSERT|UPDATE|DELETE] ON table_name
FOR EACH ROW [FOLLOWS|PRECEDES existing_trigger_name]
BEGIN

END$$
DELIMITER ;
 You put the trigger name after the CREATE TRIGGER
statement. The trigger name should follow the naming
convention [trigger time]_[table name]_[trigger event], for
example before_employees_update.

Poonam Railkar, SKNCOE


 Trigger activation time can be BEFORE or AFTER. You must
specify the activation time when you define a trigger. You use
the BEFORE keyword if you want to process action prior to
the change is made on the table and AFTER if you need to
process action after the change is made.
 The trigger event can be INSERT, UPDATE or DELETE. This
event causes the trigger to be invoked. A trigger only can be
invoked by one event. To define a trigger that is invoked by
multiple events, you have to define multiple triggers, one for
each event.
 A trigger must be associated with a specific table. Without a
table trigger would not exist therefore you have to specify the
table name after the ON keyword.
 You place the SQL statements between BEGIN and END
block. This is where you define the logic for the trigger.
CREATE TRIGGER before_employee_update
BEFORE UPDATE ON employees

Poonam Railkar, SKNCOE


FOR EACH ROW
BEGIN
declare op varchar(20);
set op = "update";
INSERT INTO
employees_audit(employeeNumber,lastname
,changedat,action) values
(OLD.employeeNumber, OLD.lastname,
NOW(),op);
END$$
mysql> select * from employees;
| employeeNumber | lastname | email |
+----------------+----------+----------------+
| 101 | Railkar | pnr@gmail.com |
| 102 | Mate | mate@yahoo.com |

mysql> select * from employees_audit;

Poonam Railkar, SKNCOE


Empty set (0.02 sec)

mysql> UPDATE employees SET lastName = 'Jagtap' WHERE


employeeNumber = 102;
Query OK, 1 row affected (0.08 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from employees_audit;


+----+----------------+----------+---------------------+--------+
| id | employeeNumber | lastname | changedat | action |
+----+----------------+----------+---------------------+--------+
| 1| 102 | Mate | 2017-07-20 10:14:01 | update |
LIST OUT TRIGGERS ON TABLES
SELECT
*

Poonam Railkar, SKNCOE


FROM
information_schema.triggers
WHERE
trigger_schema = 'database_name'
AND event_object_table = 'table_name';

 DROP TRIGGER table_name.trigger_name;


Poonam Railkar, SKNCOE
In Oracle
Types of Triggers in Oracle

Row-Level Triggers
Row-level triggers execute once for each row in a transaction. Row-level

Poonam Railkar, SKNCOE


triggers are created using the for each row clause in the create trigger
command. For instance if we insert in a single transaction 20 rows to the
table EMPLOYEE, the trigger is executed 20 times.

Statement-Level Triggers
Statement-level triggers execute once for each transaction. When we insert in
one transaction 20 rows to EMPLOYEE table , then statement-level trigger
is executed only once.
Schema – Event –
Employee Delete on
LeftOutEmployee Employee
When an employee leaves the company his record is deleted from

Poonam Railkar, SKNCOE


Employee Table,
but must be added to LeftOutEmployee for future reference.

Action – Insert
on
LeftOutEmploy
ee
The Example for creating a trigger is:
create or replace trigger trigger1
after delete on Employee
for each row
begin
insert into LeftOutEmployee values

Poonam Railkar, SKNCOE


(:OLD.eid, :OLD.ename, :OLD.sal);
dbms_output.put_line
('Record added to LeftOutEmployees');
end;
For Example: The price of a product changes constantly. It is important to
maintain the history of the prices of the products.
We can create a trigger to update the 'product_price_history' table when the
price of the product is updated in the 'product' table.

1) Create the 'product' table and 'product_price_history' table

Poonam Railkar, SKNCOE


CREATE TABLE product_price_history
(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );

CREATE TABLE product


(product_id number(5),
product_name varchar2(32),
supplier_name varchar2(32),
unit_price number(7,2) );
2) Create the price_history_trigger and execute it
.
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price ON product
FOR EACH ROW
BEGIN

Poonam Railkar, SKNCOE


INSERT INTO product_price_history
VALUES (:old.product_id, :old.product_name, :old.supplier_name,
:old.unit_price);
END;

3) Lets update the price of a product.


UPDATE PRODUCT SET unit_price = 800 WHERE
product_id = 100 Once the above update query is executed,
the trigger fires and updates the 'product_price_history'
table.
1)BEFORE UPDATE, Statement Level: This trigger will insert a record into the table
'product_check' before a sql update statement is executed, at the statement level.

CREATE or REPLACE TRIGGER Before_Update_Stat_product


BEFORE UPDATE ON product
Begin

Poonam Railkar, SKNCOE


INSERT INTO product_check
Values('Before update, statement level',sysdate());
END;
/
2) BEFORE UPDATE, Row Level: This trigger will insert a record into the table
'product_check' before each row is updated.
CREATE or REPLACE TRIGGER Before_Upddate_Row_product
BEFORE UPDATE ON product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('Before update row level',sysdate());
END;
/
3) AFTER UPDATE, Statement Level: This trigger will insert a record into the table
'product_check' after a sql update statement is executed, at the statement level.

CREATE or REPLACE TRIGGER After_Update_Stat_product


AFTER UPDATE ON product
BEGIN
INSERT INTO product_check
Values('After update, statement level', sysdate);

Poonam Railkar, SKNCOE


End;
/

4) AFTER UPDATE, Row Level: This trigger will insert a record into the table
'product_check' after each row is updated.

CREATE or REPLACE TRIGGER After_Update_Row_product


AFTER insert On product
FOR EACH ROW
BEGIN
INSERT INTO product_check
Values('After update, Row level',sysdate);
END;
/
Create trigger to check_balance before withdrawal if balance
sufficient then withdraw same amount otherwise withdraw only
amount which is available.
Account( ac_nmr, name, amount)
Tranaction(acc_number, C_D, cd_amount)

Create Trigger CHECK_BALANCE before INSERT ON


TRANSACTION
FOR EACH ROW
Begin
declare amt integer;
IF NEW.C_D ="D" THEN
select amount into amt from account
where ac_nmr=new.acc_nmbr;
IF amt < NEW.cd_amount THEN
Set NEW.cd_amount= amt;
END IF;
END IF;
End$
Account( ac_nmr, name, amount)
Tranaction(acc_number, C_D, cd_amount)

CREATE TRIGGER UPDATE_BALANCE AFTER INSERT ON


TRANSACTION
FOR EACH ROW
BEGIN
IF NEW.C_D ="C" THEN
UPDATE ACCOUNT
SET AMOUNT =AMOUNT+NEW.CD_AMOUNT
where ac_nmr=NEW.acc_nmbr;
ELSE
UPDATE ACCOUNT
SET AMOUNT =AMOUNT-NEW.CD_AMOUNT
where ac_nmr=NEW.acc_nmbr;
END IF;
END$
CREATE MULTIPLE TRIGGERS FOR THE SAME TRIGGER
EVENT AND ACTION TIME
DELIMITER $$
CREATE TRIGGER trigger_name
[BEFORE|AFTER] [INSERT|UPDATE|DELETE] ON table_name
FOR EACH ROW [FOLLOWS|PRECEDES] existing_trigger_name
BEGIN

END$$
DELIMITER ;
DELIMITER $$
DELIMITER $$ CREATE TRIGGER
before_products_update_2
CREATE TRIGGER before_products_update BEFORE UPDATE ON products
BEFORE UPDATE ON products FOR EACH ROW FOLLOWS
FOR EACH ROW before_products_update
BEGIN BEGIN
INSERT INTO INSERT INTO
price_logs(product_code,price) user_change_logs(product_code,updated_by)
VALUES(old.productCode,old.msrp); VALUES(old.productCode,user());
END$$ END$$

DELIMITER ; DELIMITER ;
 Alter Triggger trig_ Name disable/enable
 Disable/Enable Triggger trig_ Name

 To remove:
 Drop Trigger Trig_Name

 If you drop a table, any triggers for the table are also dropped.

 SHOW TRIGGERS FROM database_name [LIKE expr | WHERE


expr];
 SHOW triggers Like 'animals' (animals is table name)
 SHOW TRIGGERS;
 SHOW TRIGGERS FROM classicmodelsDB;
 SHOW TRIGGERS FROM classicmodelsDB WHERE `table` = 'employees';
 SELECT * FROM information_schema.triggers
WHERE trigger_schema = 'database_name‘ AND
event_object_table = 'table_name';
CURSORS
 Oracle creates a memory area, known as context area, for
processing an SQL statement, which contains all
information needed for processing the statement, for
example, number of rows processed etc.
 A cursor is a pointer to this context area. PL/SQL controls

Poonam Railkar, SKNCOE


the context area through a cursor. A cursor holds the rows
(one or more) returned by a SQL statement. The set of
rows the cursor holds is referred to as the active set.
 You can name a cursor so that it could be referred to in a
program to fetch and process the rows returned by the
SQL statement, one at a time. There are two types of
cursors:
 Implicit cursors
 Explicit cursors
IMPLICIT CURSORS
 Implicit cursors are automatically created by Oracle
whenever an SQL statement is executed, when there
is no explicit cursor for the statement.
Programmers cannot control the implicit cursors

Poonam Railkar, SKNCOE



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 need 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 the attributes like%FOUND, %ISOPEN,
%NOTFOUND, and %ROWCOUNT.
The following table provides the description of the most used attributes:

Poonam Railkar, SKNCOE


 Any SQL cursor attribute will be accessed as
sql%attribute_name as shown below in the the
example.
 Example: Consider following table

Poonam Railkar, SKNCOE


The following program would update the table and increase 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

Poonam Railkar, SKNCOE


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 SQL prompt, it produces the
following result:
.

If you check the records in customers table, you will find that

Poonam Railkar, SKNCOE


the rows have been updated:
Select * from customers;
EXPLICIT CURSORS
 Explicit cursors are programmer defined cursors for gaining
more control over the context area. An explicit cursor should be
defined in the declaration section of the PL/SQL Block. It is
created on a SELECT Statement which returns more than one

Poonam Railkar, SKNCOE


row.
 The syntax for creating an explicit cursor is :
CURSOR cursor_name IS select_statement; (in oracle)
CURSOR cursor_name for select_statement; (in mysql)
Working with an explicit cursor involves four steps:
 Declaring the cursor for initializing in the memory
 Opening the cursor for allocating memory
 Fetching the cursor for retrieving data
 Closing the cursor to release allocated memory
Example: (Oracle)
Following is a complete example to illustrate the concepts of explicit cursors:

DECLARE
c_id customers.id%type;
c_name customers.name%type;

Poonam Railkar, SKNCOE


c_addr customers.address%type;
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;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
EXIT WHEN c_customers%notfound;
END LOOP;
CLOSE c_customers;
END;
/
When the above code is executed at SQL prompt, it
produces the following result:

Poonam Railkar, SKNCOE


RECORD TYPES

Bordoloi and Bock


• A table-based record is one whose structure is
drawn from the list of columns in the table.
• A cursor-based record is one whose structure
matches the elements of a predefined cursor.
• To create a table-based or cursor_based record
use the %ROWTYPE attribute.
EXAMPLE

Bordoloi and Bock


 DECLARE
 vr_student student%ROWTYPE;
 BEGIN
 SELECT *
 INTO vr_student
 FROM student
 WHERE student_id = 156;
 DBMS_OUTPUT.PUT_LINE (vr_student.first_name||‘
’||vr_student.last_name|| ‘ has an ID of 156’);
 EXCEPTION
 WHEN no_data_found
 THEN
 RAISE_APPLICATION_ERROR(‘The Student is not in the
database’);
 END;
Explicit Cursor in MySQL
When the cursor is no longer used, you should close it.
When working with MySQL cursor, you must also declare a NOT FOUND handler to
handle the situation when the cursor could not find any row. Because each time you call
the FETCH statement, the cursor attempts to read the next row in the result set. When the
cursor reaches the end of the result set, it will not be able to get the data, and a condition
is raised. The handler is used to handle this condition.

To declare a NOT FOUND handler, you use the following syntax:


DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

Variable
Where finished is a variable to indicate that the cursor has reached the end of the
result set. Notice that the handler declaration must appear after variable and
cursor declaration inside the stored procedures.

The following diagram illustrates how MySQL cursor works.


CREATE PROCEDURE build_email_list (INOUT email_list
varchar(4000))
BEGIN
DECLARE v_finished INTEGER DEFAULT 0;
DECLARE v_email varchar(255) DEFAULT "";
-- declare cursor for employee email Comments
DEClARE email_cursor CURSOR FOR
SELECT email FROM employees;

Poonam Railkar, SKNCOE


-- declare NOT FOUND handler Comments
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET v_finished = 1;
OPEN email_cursor;
get_email: LOOP
FETCH email_cursor INTO v_email;
IF v_finished = 1 THEN
LEAVE get_email;
END IF;
-- build email list
SET email_list = CONCAT(v_email,";",email_list);
END LOOP get_email;
CLOSE email_cursor;
end $$
mysql> delimiter ;
mysql> SET @email_list = "";
Query OK, 0 rows affected (0.00 sec)

mysql> CALL build_email_list(@email_list);

Poonam Railkar, SKNCOE


Query OK, 0 rows affected (0.01 sec)

mysql> SELECT @email_list;


+-------------------------------+
| @email_list |
+-------------------------------+
| mate@yahoo.com;pnr@gmail.com; |
+-------------------------------+
1 row in set (0.00 sec)
CREATE PROCEDURE curdemo()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE a CHAR(16);
DECLARE b, c INT;
DECLARE cur1 CURSOR FOR SELECT id,data FROM test_t1;
DECLARE cur2 CURSOR FOR SELECT i FROM test_t2;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur1;

Poonam Railkar, SKNCOE


OPEN cur2;
read_loop: LOOP
FETCH cur1 INTO a, b;
FETCH cur2 INTO c;
IF done THEN
LEAVE read_loop;
END IF;
IF b < c THEN
INSERT INTO test_t3 VALUES (a,b);
ELSE
INSERT INTO test_t3 VALUES (a,c);
END IF;
END LOOP;
CLOSE cur1;
CLOSE cur2;
END;
-- Declare continue handler

Poonam Railkar, SKNCOE


DECLARE CONTINUE HANDLER FOR
SQLSTATE '02000' SET done=1;

Or

DECLARE CONTINUE HANDLER


FOR NOT FOUND SET done = 1;
PL/SQL PARAMETERIZED CURSOR
 PL/SQL Parameterized cursor pass the parameters
into a cursor and use them in to query.

Poonam Railkar, SKNCOE


 PL/SQL Parameterized cursor define only datatype
of parameter and not need to define it's length.
 Default values is assigned to the Cursor parameters.
and scope of the parameters are locally.
 Parameterized cursors are also saying static cursors
that can passed parameter value when cursor are
opened.
 Scope of the parameters are locally

 You can assign default value to a cursor parameter.


Cursor display employee information from
emp_information table whose emp_no four (4).

SQL>set serveroutput on SQL>edit parameter_cursor_demo


DECLARE cursor c(no number) is select * from
emp_information where emp_no = no; tmp
emp_information%rowtype; BEGIN OPEN c(4); FOR tmp IN

Poonam Railkar, SKNCOE


c(4) LOOP dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name: '||tmp.emp_name);
dbms_output.put_line('EMP_Dept: '||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salary);
END Loop; CLOSE c; END; /

SQL>@parameter_cursor_demo
EMP_No: 4
EMP_Name: Zenia Sroll
EMP_Dept: Web Developer
EMP_Salary: 42k

PL/SQL procedure successfully completed.


SYNTAX FOR EXCEPTION HANDLING
 An exception is an error condition during a program execution. PL/SQL
supports programmers to catch such conditions using EXCEPTION block
in the program and an appropriate action is taken against the error
condition. There are two types of exceptions −
 System-defined exceptions

Poonam Railkar, SKNCOE


 User-defined exceptions

DECLARE <declarations section>


BEGIN <executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
........
WHEN others THEN
exception3-handling-statements END;
DECLARE c_id customers.id%type := 8;
c_name customers.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr FROM

Poonam Railkar, SKNCOE


customers WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN dbms_output.put_line('No such
customer!');
WHEN others THEN dbms_output.put_line('Error!'); END; /

The above program displays the name and address of a


customer whose ID is given. Since there is no customer
with ID value 8 in our database, the program raises the
run-time exception NO_DATA_FOUND, which is captured
in the EXCEPTION block.
USER-DEFINED EXCEPTIONS
The syntax for declaring an exception is −
DECLARE my-exception EXCEPTION;

Poonam Railkar, SKNCOE


PL/SQL allows you to define your own exceptions
according to the need of your program.
A user-defined exception must be declared and
then raised explicitly, using RAISE statement
DECLARE c_id customers.id%type := &cc_id;
c_name customer.name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0

Poonam Railkar, SKNCOE


THEN RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr FROM
customers WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id
THEN dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found
THEN dbms_output.put_line('No such customer!');
WHEN others THEN dbms_output.put_line('Error!');
END; /
 Enter value for cc_id: -6 (let's enter a value -6)
 old 2: c_id customers.id%type := &cc_id;

Poonam Railkar, SKNCOE


 new 2: c_id customers.id%type := -6;

 ID must be greater than zero!

 PL/SQL procedure successfully completed.


PREDEFINED EXCEPTIONS
 Exception :: Oracle Error ::: SQLCODE ::: Description
 ZERO_DIVIDE :: 01476 :: -1476 ::It is raised
when an attempt is made to divide a number by zero.

Poonam Railkar, SKNCOE


 CASE_NOT_FOUND :: 06592 :: -6592 ::
It is raised when none of the choices in the WHEN
clause of a CASE statement is selected, and there is no
ELSE clause.
 INVALID_CURSOR :: 01001:: -1001:: It is
raised when attempts are made to make a cursor operation
that is not allowed, such as closing an unopened cursor.
 NO_DATA_FOUND :: 01403 :: +100 ::
It is raised when a SELECT INTO statement returns
no rows.
 ROWTYPE_MISMATCH :: 06504:: -6504:: It is
raised when a cursor fetches value in a variable having
incompatible data type.
UPDATES THROUGH CURSORS
Can update tuples fetched by cursor by declaring that the cursor is
for update
declare c cursor for
select *
from account

Poonam Railkar, SKNCOE


where branch_name = ‘Perryridge’
for update
To update tuple at the current location of cursor c
update account
set balance = balance + 100
where current of c
ASSERTIONS

⚫ An expression that should be always true

⚫ When created, the expression must be true

⚫ DBMS checks the assertion after any change that


may violate the expression

Must return True or False

68
EXAMPLE 1

Sum of loans taken by a customer does not


exceed 100,000 Must return True or
False (not a relation)
Create Assertion SumLoans Check
( 100,000 >= ALL
Select Sum(amount)
From borrower B , loan L
Where B.loan_number = L.loan_number
Group By customer_name );

69
EXAMPLE 2

Number of accounts for each customer in a given


branch is at most two

Create Assertion NumAccounts Check


( 2 >= ALL
Select count(*)
From account A , depositor D
Where A.account_number =
D.account_number
Group By customer_name, branch_name );
70
Poonam Railkar, SKNCOE
Roles and privileges
CREATING USERS

 The DBA creates users by using the CREATE


USER statement.

Poonam Railkar, SKNCOE


CREATE USER user
IDENTIFIED BY password;

SQL> CREATE USER scott


2 IDENTIFIED BY tiger;
User created.
USER SYSTEM PRIVILEGES
• Once a user is created, the DBA can grant specific system
privileges to a user.

GRANT privilege [, privilege...]


TO user [, user...];

Poonam Railkar, SKNCOE


• An application developer may have the following system
privileges:
– CREATE SESSION
– CREATE TABLE
– CREATE SEQUENCE
– CREATE VIEW
– CREATE PROCEDURE
AUTHORIZATION
Forms of authorization on parts of the database:
 Read - allows reading, but not modification of data.
 Insert - allows insertion of new data, but not modification
of existing data.

Poonam Railkar, SKNCOE


 Update - allows modification, but not deletion of data.
 Delete - allows deletion of data.

Forms of authorization to modify the database schema


 Index - allows creation and deletion of indices.
 Resources - allows creation of new relations.
 Alteration - allows addition or deletion of attributes in a
relation.
 Drop - allows deletion of relations.
Poonam Railkar, SKNCOE
END UNIT II ☺
Poonam Railkar, SKNCOE
UNIT II QUESTION BANK
Poonam Railkar, SKNCOE
QUESTION BANK
2010 DEC
Poonam Railkar, SKNCOE
2011 April

3. a) List difference between embedded SQL and Dynamic SQL. [6]


b) Explain the different operations of Relational Algebra. [5]
Consider the following Relations. It defines the schema of the database
application for a bank. It manages the branches and customers of the bank.
Customers take loans (borrow money) or open accounts (deposit money) at

Poonam Railkar, SKNCOE


one or more branches. [6]
Branch (B_No, B_name, B_city, asset), Customer (C_No,C_Name, C_city
street)Loan(Loan_no, B_name, amount), Account (Acc_No, B_name,
Balance) Borrower (C_No, Loan_No), Depositor (C_No, Acc_No)
Answer the following queries in each of the query languages that you know :
1) Find the names and address of customers who have a loan.
2) Find loan data, ordered by decreasing amounts, then increasing loan
numbers.
3) Find the pairs of names of different customers who live at the same
address but have accounts at different branches.
4. a) Explain Assertion and Triggers with suitable example. 6
b) Explain Stored procedure and stored function.
Consider the following Relations. It defines the schema of the database
application for a library. 5
Book (Book_ISBN [pk], Title, Publisher_Name [fk]) 6
BOOK_AUTHORS (Book_ISBN [pk, fk], Author_Name [pk])
PUBLISHER(Name [pk], Address, Phone)
BOOK_COPIES (Book_ISBN [pk, fk], Branch_ID [pk, fk], Num_Copies)

Poonam Railkar, SKNCOE


BOOK_LOANS (Book_ISBN [pk,fk], Branch_ID [pk, fk], Card_Num
[pk, fk], Date_Out, Date_Due)
LIBRARY_BANCH (Branch_ID[pk], Branch_Name, Address)
BORROWER (Card_Num [pk], Name, Address, Phone)
Answer the following queries in each of the SQL query languages that you
know :
1) List the ISBN and title of all books written by “John Smith”.
2) List the ISBN and title of all books written by “John Smith” as the only
author.
3) List the Card number and name of all borrowers who checked out two
or more books on 10/16/2003.
4) List the branch ID and name of all library branches that have at least one
copy of all the books.
2011 DEC
3. a) What are different types of joins in SQL ? Explain with suitable example. 6
b) Write short note on Dynamic SQL. 6
c) Consider following database :
Student (Roll_no, Name, Address)
Subject (Sub_code, Sub_name)

Poonam Railkar, SKNCOE


Marks (Roll_no, Sub_code, marks)
Write following queries in SQL :
i) Find average marks of each student, along with the name of student.
ii) Find how many students have failed in the subject “DBMS”. 4
4. a) What is cursor ? Explain explicit cursor and reference cursor in PL/SQL with
suitable example. 6
b) What is stored procedure and function ? 4
c) Consider the relational database
dept (dept_no, dname, loc, mgrcode)
emp (emp_no, ename, designation)
project (proj_no, proj_name, status)
dept. and emp. are related as 1 to many.
Project and emp are related as 1 to many.

Poonam Railkar, SKNCOE


Write queries for the following :
i) Give the names of employees who are working on ‘Blood Bank’ project.
ii) Give the name of managers from ‘MARKETING’ department.
iii) Give all the employees working under status ‘INCOMPLETE’ projects.
6
Poonam Railkar, SKNCOE
2012 APRIL
Poonam Railkar, SKNCOE
2012 DEC
APRIL 2013
Q3 A) Given relation schema: R(A,B,C), S(D,E,F). Let relation
r(R) and s(S) be given. Convert following SQL Statements in
relational algebra form. [8]
1. Select * from r where B = 17
2. Select A,F from r,s where r.C = s.D

Poonam Railkar, SKNCOE


3. Update r, set B = B*15 where A=’aaa’
4. Select * from s where E < 20
B) Explain various operators in relational Algebra. [8]
Q4 A) What is cursor? Explain various types of Cursor. [8]
B) Explain Stored Procedures and Triggers.
[8]
OTHER QUESTIONS
1. Describe the circumstances in which you would choose to
use embedded SQL rather than SQL alone or only a
general-purpose programming language.
2. Write short note on dynamic and embedded SQL
3. Specify the need of Embedded SQL. List and Explain

Poonam Railkar, SKNCOE


various embedded sql commands.
4. What is the use of “declare cursor statements with the
embedded SQL?
5. Explain various SQL DML Commands.
6. Give SQL command for Database modification.
7. Give commands for creating table, modifying and deleting.
8. Explain views.
9. Explain views updating with example.
10. Explain database modification using SQL Insert, Update
and delete queries.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy