0% found this document useful (0 votes)
8 views16 pages

U2t6 Mysql PL SQL

PL/SQL, or Procedural Language Extension of SQL, combines SQL's data manipulation capabilities with procedural programming features, allowing for complex operations and control structures. It supports static and dynamic SQL, offers robust error handling, and facilitates the creation of stored procedures and functions for various database operations. The document outlines the syntax, advantages, and examples of using PL/SQL, including how to create, call, and manage procedures and functions, as well as error handling and cursor usage.

Uploaded by

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

U2t6 Mysql PL SQL

PL/SQL, or Procedural Language Extension of SQL, combines SQL's data manipulation capabilities with procedural programming features, allowing for complex operations and control structures. It supports static and dynamic SQL, offers robust error handling, and facilitates the creation of stored procedures and functions for various database operations. The document outlines the syntax, advantages, and examples of using PL/SQL, including how to create, call, and manage procedures and functions, as well as error handling and cursor usage.

Uploaded by

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

PL/SQL

 PL/SQL stands for “procedural language extension of SQL”.


 SQL stands for structured query language (i.e) used to perform operations on the records in
database such as INSERTING records, UPDATING records , DELETING records , CREATING ,
MODIFYING , and DROPPING tables , VIEWS, etc.,
 Although PL/SQL is closely integrated with SQL language, yet it adds some programming constraints
that are not available in SQL.
 The PL/SQL is known for its combination of data manipulating power of SQL with data processing
power of procedural language.
 The programs of PL/SQL are logical blocks that can contain any number of nested sub-blocks.
 PL/SQL includes all topics of PL/SQL languages such as
o Conditional statements
o Loops
o Arrays
o Strings
o Exception
o Collections
o Records
o Triggers
o Functions
o Procedures
o Cursors
 It inherits the robustness , security , and portability of the Oracle database.

ADVANTAGES
 PL/SQL supports both static and dynamic SQL.
 Static SQL supports DML operations and transaction control from PL/SQL block.
 In Dynamic SQL , SQL allows embedding DDL statements in PL/SQL blocks.
 PL/SQL allows sending an entire block of statements to the database at one time.
 This reduces network traffic and provides high performance for the applications.
 PL/SQL saves time on design and debugging by strong features ,such as
o Exception handling
o Encapsulation
o Data hiding
o OO data types
 PL/SQL is portable , provides high security level, provides access to predefined SQL packages.
 PL/SQL provides support for developing web applications and server pages.
General Structure of PL/SQL

DECLARE It is Optional


Variable_declaration
BEGIN It is mandatory
Executable_Statements
Exception  it is Optional
Exception_Handling
END it is Mandatory

1. create database krish;


2. use krish;
3. create table inventory( prono numeric, proname varchar(30), rate numeric(10,2), constraint
prono_pk primary key(prono));

4. INSERT INTO inventory(prono,proname,rate) VALUES (100,"PEN",12),(101,"PENCIL",20),


(102,"SCALE",30),(103,"BOX",100);
5. select *from inventory;

HOW TO CREATE A procedure

create procedure get_all_records()


BEGIN
select *from inventory;
END

 If u give above query the Mysql compiler will give error because
 Usually in sql all the queries end with ; ( semicolon) , so compiler will understood it
 This semicolon is called ( DELIMITER)
 Generally in mysql default delimiter is ; ( semicolon)
 In above program leads error because we have used delimiter at the end of (select *From
inventory ; )
 So it terminate there it won’t execute the (END) query
 So we can change the delimiter while creating large statement as procedure
DELIMITER $$  here we have change delimiter as $$
create procedure get_all_records()
BEGIN
select *from inventory;
END$$
DELIMITER ;  here we have change default delimiter

Select all the above queries and click execute icon , now we got the stored_procedure in the left screen
like as following

How to call the Procedure ?


call get_all_records();

How to Drop procedure


drop procedure get_all_records;
drop procedure if exists get_all_records;

Addition of two number using stored_procedure


DELIMITER $$
create procedure summation()
BEGIN
DECLARE a INT DEFAULT 100;
DECLARE b INT DEFAULT 200;
DECLARE C INT;
SET C=a+b;
Select C;
END$$
DELIMITER ;
call summation();
Count Number of products in store without stored procedure
select count(prono) from inventory;

Count Number of products in store using stored procedure


DELIMITER $$
create procedure find_total_product()
BEGIN
DECLARE no_of_product INT DEFAULT 0;
select count(prono) from inventory into no_of_product;
Select no_of_product;
END$$
DELIMITER ;

call find_total_product();

How to pass parameter to Stored_Procedure


In mysql there 3-types of parameters
1. IN
2. OUT
3. INOUT
IN?
IN means something is going to come inside of stored procedure
OUT?
OUT mean something is going to out from stored procedure
IN/OUT?
IN/OUT something will come inside of procedure and something is also out from the procedure

FIND no_of_product _rate is greater than 50 rs using (IN)


DELIMITER $$
create procedure filter1(IN f1 int)
BEGIN
DECLARE no_of_product INT DEFAULT 0;
select count(prono) into no_of_product from inventory where rate>f1;
Select no_of_product;
END$$
DELIMITER ;
call filter1(50);

OUT
DELIMITER $$
create procedure filter2(IN f1 int,OUT res int)
BEGIN
select count(prono) into res from inventory where rate>f1;
END$$
DELIMITER ;
call filter2(50,@res);
select @res;
call filter2(10,@res);
select @res;
/* here @res called session variable like as global variable */

IN/OUT
DELIMITER $$
create procedure increment(IN i int,INOUT res int)
BEGIN
set res=res+i;
END$$
DELIMITER ;
set @inc=100;
call increment(150,@inc);
select @inc;
call increment(150,@inc);
select @inc;
IF_ELSE_Statement
use krish;
select *from inventory;
DELIMITER $$
create procedure get_product_name(IN pid int)
BEGIN
if pid=100 THEN
select 'PEN';
elseif pid=101 THEN
select "PENCIL" ;
elseif pid=102 then
select "SCALE" ;
else
select "product not found";
end if;
END$$
DELIMITER ;
call get_product_name(100);

SWITCH CASE
DELIMITER $$
create procedure get_product_name1(IN pid int)
BEGIN
case pid
when 100 then
select "PEN";
when 101 then
select "PENCIL";
when 102 then
select "SCALE";
end case;
END$$
DELIMITER ;
call get_product_name1(102);

HOW TO insert a record using stored_procedure


DELIMITER $$
create procedure insert_product(IN pid int,IN pname varchar(30),IN r numeric(5,2))
BEGIN
insert into inventory values(pid,pname,r);
END$$
DELIMITER ;
call insert_product(105,"sketch",30);
select *from inventory;

LOOP
DELIMITER $$
create procedure loopdemo()
BEGIN
DECLARE i INT;
SET i=1;
krish:loop
SELECT i;
END loop;
END $$
DELIMITER ;
call loopdemo();

if run the above loop is called infinite loop ..we can solve it like as following

DELIMITER $$
create procedure loopdemo()
BEGIN
DECLARE i INT;
SET i=1;
krish:loop
if i>10 THEN
leave krish;
end if;
SELECT i;
SET i=i+1;
END loop;
END $$
DELIMITER ;
call loopdemo();
in above output we got the result in separate window if u want to complain all the output in same window

DELIMITER $$
create procedure loopdemo()
BEGIN
DECLARE i INT;
DECLARE str varchar(30);
SET i=1;
SET str='';
krish:loop
if i>10 THEN
leave krish;
end if;
SET str=CONCAT(str,i,' ');
SET i=i+1;
END loop;
select str;
END $$
DELIMITER ;
FUNTIONS
1. CREATE TABLE users(id INT primary key, sname VARCHAR(50), age INT ,gender varchar(10),city
varchar(30),contact varchar(30));
2. INSERT INTO users(id,sname,age,gender,city,contact) VALUES
(100,'Ravi',23,'Male','Namakkal','9876543210'),
(101,'Sara',23,'Female','Erode','9874521360'),
(102,'mahi',18,'female','salem','9994477191'),
(103,'jeni',22,'female','chennai','9894585056');
3. select *from users;
Here we are going to do when user will enter ID no , we want to get city name and their contact number
with help of function
Example
delimiter $$
CREATE FUNCTION add_numbers (a INT, b INT)
RETURNS INT // here we are return the final result as integer that why here we mention INT
DETERMINISTIC
BEGIN
declare c int;
set c=a+b;
RETURN c;
END$$
delimiter ;
select add_numbers(5,2);

Get Mobile number with city


delimiter $$
CREATE FUNCTION get_mob_city (sid INT)
RETURNS varchar(900)
DETERMINISTIC
BEGIN
declare full_details varchar(50);
select concat(city,'---',contact) into full_details
from users
where id=sid;
return full_details;
END$$
delimiter ;
select sname,get_mob_city(id) from users;
ERROR-HANDLING
delimiter $$
create procedure insert_Record(IN sid int,IN name varchar(30),IN a int , IN g varchar(10),IN c
varchar(30),con varchar(10))
BEGIN
insert into users values(sid,name,a,g,c,con);
select * from users;
END $$
delimiter ;
call insert_Record(100,"krish",35,"Male","tirupur","9994974215");
 while inserting the above record it leads error like ERROR CODE :1062 “duplicate entry “100” for
keys “user.PRIMARY”
 for this reason the next line ( select *from users) is not executed , so we can solve this problem with
the help of EXCEPTION handler
Handling the Error using ( continue)
 Here continue means in your query is there any error occurred means , it won’t terminate entire
query , it will move to next query to execute
delimiter $$
create procedure insert_Record(IN sid int,IN name varchar(30),IN a int , IN g varchar(10),IN c
varchar(30),con varchar(10))
BEGIN
declare continue handler for 1062
BEGIN
select concat("This",sid," Alerady exists in the table try to add different ID");
END;
insert into users values(sid,name,a,g,c,con);
select *from users;
END $$
delimiter ;
call insert_Record(100,"krish",35,"Male","tirupur","9994974215");

 In above example we have error in our query but it execute ( select) query
Using Exit
delimiter $$
create procedure insert_Record(IN sid int,IN name varchar(30),IN a int , IN g varchar(10),IN c
varchar(30),con varchar(10))
BEGIN
declare exit handler for 1062
BEGIN
select concat("This",sid," Alerady exists in the table try to add different ID");
END;
insert into users values(sid,name,a,g,c,con);
select *from users;
END $$
delimiter ;
call insert_Record(100,"krish",35,"Male","tirupur","9994974215");

CURSOR
 If u want to do some process for each and every from a table with the help of cursor
 Cursor will move each and every row in a table for doing some process
 Here we are going to take backup all data(rows) from table(users) to (employees) table with the
help of cursor

CREATE TABLE employees(id INT primary key, sname VARCHAR(50), age INT ,gender varchar(10),city
varchar(30),contact varchar(30),salary numeric(10,2));
delimiter $$
create procedure backu_Employee()
begin
declare done int default 0;
declare bid,bage,bsalary int;
declare bname,bgender,bcity,bcontact varchar(30);
declare cur cursor for select *from users;
declare exit handler for not found set done=1;
delete from employees;
open cur;
krish:loop
if done=1 then
leave krish;
end if;
fetch cur into bid,bname,bage,bgender,bcity,bcontact,bsalary;
insert into employees values(bid,bname,bage,bgender,bcity,bcontact,bsalary);
end loop;
close cur;
end $$
delimiter ;
call backu_Employee();
select *from employees;

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