Stored procedure
STORED PROCEDURE
Anjali g
anjalig2009@gmail.com
www.facebook.com/AnjaliG
eetha
twitter.com/AnjaliGeetha
in.linkedin.com/in/Anjali G
9497879952
What is stored procedure?
• A stored procedure is a subroutine available to applications that access a relational
database system.
• Extensive or complex processing that requires execution of several SQL statements
is moved into stored procedures, and all applications call the procedures.
• Typical uses for stored procedures include data validation (integrated into the
database) or access control mechanisms
• stored procedures can consolidate and centralize logic that was originally
implemented in applications.
Why do we use stored procedures?
• stored procedures should run faster
-Once created, stored procedures are compiled and stored in the
database
• saving resources
-code is stored in a pre-compiled form ;syntactically valid and does not
need to be compiled at run-time
• improving the scalability of applications
-each user of the stored procedure will use exactly the same form of
queries which means the queries are reused
One Query
Wait, receive, process/compute
Database
Server
Internet
• less network traffic
-instead of sending multiple lengthy SQL statements, the application has to
send only name and parameters of the stored procedure
• Stored procedures are secure.
- Database administrator can grant appropriate permissions to applications
that access stored procedures in the database without giving any permission on
the underlying database tables.
Disadvantages…
• For a lot of stored procedures, the memory usage of every connection will increase
substantially.
• Overuse a large number of logical operations inside store procedures, the CPU
usage will also increase because database server is not well-designed for logical
operations.
• A constructs of stored procedures make it more difficult to develop stored
procedures that have complicated business logic.
• It is difficult to debug stored procedures. Only few database management systems
allow you to debug stored procedures
• It is not easy to develop and maintain stored procedures; Required specialized skill
set that not all application developers possess
Working with Stored Procedures
mysql> CREATE DATABASE db5;
Query OK, 1 row affected (0.01 sec)
mysql> USE db5;
Database changed
mysql> CREATE TABLE t (s1 INT);
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO t VALUES (5);
Query OK, 1 row affected (0.00 sec)
mysql> DELIMITER //
• The delimiter is the character or string of characters that you'll use to tell the mysql
client that you've finished typing in an SQL statement
CREATE PROCEDURE p1 () SELECT * FROM t; //
- Procedure Names are not case sensitive, so 'p1' and 'P1' are the same name.
-“() “ is the 'parameter list'.
- last part of the statement is the procedure body, which is an SQL statement .
-mysql> CALL p1() //
Characteristics Clauses:-
CREATE PROCEDURE p2 ()
LANGUAGE SQL <-- the body of the procedure is written in SQL
NOT DETERMINISTIC <-- A deterministic procedure is a procedure which will
always return the same outputs given the
same data inputs
SQL SECURITY DEFINER <-- instruction that tells the MySQL server to check the
privileges of the user
COMMENT 'A Procedure'
SELECT CURRENT_DATE, RAND() FROM t //
mysql> call p2() //
+--------------+-----------------+
| CURRENT_DATE | RAND() |
+--------------+-----------------+
| 2004-11-09 | 0.7822275075896 |
+--------------+----------
• Parameters :-
1. CREATE PROCEDURE p5 () ...
2. CREATE PROCEDURE p5 ([IN] name data-type) ...
3. CREATE PROCEDURE p5 (OUT name data-type) ...
4. CREATE PROCEDURE p5 (INOUT name data-type)
• In the first example the parameter list is empty.
• In the second example there is one input parameter. The word IN is optional
because parameters are IN (input) by default.
• In the third example there is one output parameter.
• In the fourth example there is one parameter which is both input and output.
IN example:-
mysql> CREATE PROCEDURE p5(p INT) SET @x = p //
mysql> CALL p5(12345)//
mysql> SELECT @x//
OUT example:-
mysql> CREATE PROCEDURE p6 (OUT p INT)
SET p = -5 //
mysql> CALL p6(@y)//
mysql> SELECT @y//
Compound Statements:-
• You need a BEGIN/END block whenever you have more than one statement in the
procedure
• The BEGIN/END block, also called a compound statement, is the place where you can
define variables and flow-of-control.
The New SQL Statements:-
• Variables : The statement you use to define variables in a compound statement is
DECLARE.
Example with two DECLARE statements
CREATE PROCEDURE p8 ()
BEGIN
DECLARE a INT;
DECLARE b INT;
SET a = 5;
SET b = 5;
INSERT INTO t VALUES (a);
SELECT s1 * a FROM t WHERE s1 >= b;
END; //
• You don't really define variables within the stored procedure. You define
them within the BEGIN/END block
• Notice that these variables are not like session variables
• You don't start them with an at sign (@).
• You must declare them explicitly at the start of the BEGIN/END block, along
with their data types.
• Once you've declared a variable, you can use it anywhere that you would
otherwise use any session variable, or literal, or column name.
Example with no DEFAULT clause and SET statement
CREATE PROCEDURE p9 ()
BEGIN
DECLARE a INT /* there is no DEFAULT clause */;
DECLARE b INT /* there is no DEFAULT clause */;
SET a = 5; /* there is a SET statement */
SET b = 5; /* there is a SET statement */
INSERT INTO t VALUES (a);
SELECT s1 * a FROM t WHERE s1 >= b;
END; //
• When declared without a DEFAULT clause, the initial value of a variable is always
NULL.
• You can use the SET statement to assign another value to a variable at any time.
Example with DEFAULT clause
CREATE PROCEDURE p10 ()
BEGIN
DECLARE a, b INT DEFAULT 5;
INSERT INTO t VALUES (a);
SELECT s1 * a FROM t WHERE s1 >= b;
END; //
• putting both variable declarations on the same line and using a DEFAULT clause to
set the initial value, rather than doing two separate DECLARE and SET statements.
Scope:-
CREATE PROCEDURE p11 ()
BEGIN
DECLARE x1 CHAR(5) DEFAULT 'outer';
BEGIN
DECLARE x1 CHAR(5) DEFAULT 'inner';
SELECT x1;
END;
SELECT x1;
END; //
mysql> CALL p11()//
+-------+
| x1 |
+-------+
| inner |
+-------+
+-------+
| x1 |
+-------+
| outer |
+-------+
Conditions and IF-THEN-ELSE
CREATE PROCEDURE p12 (IN parameter1 INT)
BEGIN
DECLARE variable1 INT;
SET variable1 = parameter1 + 1;
IF variable1 = 0 THEN
INSERT INTO t VALUES (17);
END IF;
IF parameter1 = 0 THEN
UPDATE t SET s1 = s1 + 1;
ELSE
UPDATE t SET s1 = s1 + 2;
END IF;
END; //
• The first thing that happens is that variable1 gets set to parameter1 plus one,
which means it gets set to zero plus one -- so it will be one.
• The next thing that happens is nothing. Since variable1 is one, the condition "if
variable1 = 0" isn't true. Therefore everything between the IF and the END IF gets
skipped.
• So now we go on to the second IF statement. And for this statement, the condition
is true, because we know that parameter1 equals zero. That's what we passed.
• And since it's true that parameter1 equals zero, this UPDATE is executed. If it had
been false, or if parameter1 had been null, the other UPDATE would have been
executed instead.
CASE:-
CREATE PROCEDURE p13 (IN parameter1 INT)
BEGIN
DECLARE variable1 INT;
SET variable1 = parameter1 + 1;
CASE variable1
WHEN 0 THEN INSERT INTO t VALUES (17);
WHEN 1 THEN INSERT INTO t VALUES (18);
ELSE INSERT INTO t VALUES (19);
END CASE;
END; //
mysql> CALL p13(1)//
WHILE ... END WHILE:-
CREATE PROCEDURE p14 ()
BEGIN
DECLARE v INT;
SET v = 0;
WHILE v < 5 DO
INSERT INTO t VALUES (v);
SET v = v + 1;
END WHILE;
END; //
• The INSERT and the SET statements here, which are between the WHILE and the
END WHILE, happen over and over until the value in variable v becomes greater
than to five.
REPEAT ... END REPEAT
CREATE PROCEDURE p15 ()
BEGIN
DECLARE v INT;
SET v = 0;
REPEAT
INSERT INTO t VALUES (v);
SET v = v + 1;
UNTIL v >= 5
END REPEAT;
END; //
• Note that there is no semicolon after the UNTIL clause in this procedure
statement.
LOOP ... END LOOP
CREATE PROCEDURE p16 ()
BEGIN
DECLARE v INT;
SET v = 0;
loop_label: LOOP
INSERT INTO t VALUES (v);
SET v = v + 1;
IF v >= 5 THEN
LEAVE loop_label;
END IF;
END LOOP;
END; //
• The LEAVE statement means "exit the loop". The actual syntax of the LEAVE statement
is the word LEAVE and a statement label.
Error Handling:-
Sample Problem: Log Of Failures
mysql> CREATE TABLE t2
s1 INT, PRIMARY KEY (s1)) //
mysql> CREATE TABLE t3 (s1 INT, KEY (s1),
FOREIGN KEY (s1) REFERENCES t2 (s1)) //
mysql> INSERT INTO t3 VALUES (5);//
...
ERROR 1216 (23000): Cannot add or update a child row: a foreign key constraint fails
CREATE TABLE error_log (error_message CHAR(80))//
< -- create error log
Exit handler:-
CREATE PROCEDURE p22 (parameter1 INT)
BEGIN
DECLARE EXIT HANDLER FOR 1216
INSERT INTO error_log VALUES (CONCAT('Time: ',current_date,
‘ Foreign Key Reference Failure For
Value = ',parameter1));
INSERT INTO t3 VALUES (parameter1);
END;//
• The word EXIT means "we'll exit from the compound statement when we're done".
Declare continue handler example :-
CREATE TABLE t4 (s1 int,primary key(s1));//
CREATE PROCEDURE p23 ()
BEGIN
DECLARE CONTINUE HANDLER
FOR SQLSTATE '23000' SET @x2 = 1;
SET @x = 1; <-- start execution
INSERT INTO t4 VALUES (1);
SET @x = 2;
INSERT INTO t4 VALUES (1);
SET @x = 3;
END;//
Declare condition :-
CREATE PROCEDURE p24 ()
BEGIN
DECLARE `Constraint Violation`
CONDITION FOR SQLSTATE '23000';
DECLARE EXIT HANDLER FOR
`Constraint Violation` ROLLBACK;
START TRANSACTION;
INSERT INTO t2 VALUES (1);
INSERT INTO t2 VALUES (1);
COMMIT;
END; //
• give the SQLSTATE or the error code another name. And then you can use that
name in a handler
Cursors:-
drop procedure if exists p25//
CREATE PROCEDURE p25 (OUT return_val INT)
BEGIN
DECLARE a,c text;
DECLARE b int;
DECLARE cur_1 CURSOR FOR SELECT flightno,details FROM tbl_flight;
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET b = 1;
OPEN cur_1;
REPEAT
FETCH cur_1 INTO a;
UNTIL b = 1
END REPEAT;
CLOSE cur_1;
SET return_val = a;
END;//
• order is important. First declare variables. Then declare conditions. Then declare
cursors. Then, declare handlers. If you put them in the wrong order, you will get an
error message.
• The first FETCH statement here will cause a single row to be retrieved from the
result set that the SELECT produced. Since we know that there are several rows in
table t, we know that this statement will happen several times -- that is, it is in a
loop.
Cursor Characteristics:-
• read only
• not scrollable
• Asensitive
READ ONLY
-Can not say
FETCH cursor1 INTO variable1;
UPDATE t1 SET column1 = 'value1' WHERE CURRENT OF cursor1;
NOT SCROLLABLE
FETCH PRIOR cursor1 INTO variable1;
FETCH ABSOLUTE 55 cursor1 INTO variable1;
• And you should avoid doing updates on a table while you have a cursor open on
the same table, because cursors are asensitive.
Thank you..
If this presentation helped you, please visit our
page facebook.com/baabtra and like it.
Thanks in advance.
www.baabtra.com | www.massbaab.com |www.baabte.com
Contact Us
Emarald Mall (Big Bazar Building)
Mavoor Road, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
NC Complex, Near Bus Stand
Mukkam, Kozhikode,
Kerala, India.
Ph: + 91 – 495 40 25 550
Start up Village
Eranakulam,
Kerala, India.
Email: info@baabtra.com

More Related Content

PPTX
Lab #2: Introduction to Javascript
PDF
Android Data Persistence
PDF
Object oriented approach in python programming
PPTX
Basics of Object Oriented Programming in Python
PDF
Introduction to Problem Solving Techniques- Python
PPTX
Templates presentation
PPT
1 Introduction To Java Technology
PDF
STL in C++
Lab #2: Introduction to Javascript
Android Data Persistence
Object oriented approach in python programming
Basics of Object Oriented Programming in Python
Introduction to Problem Solving Techniques- Python
Templates presentation
1 Introduction To Java Technology
STL in C++

What's hot (20)

PDF
5. Frames & Forms.pdf
PPT
UML Diagrams
PPTX
Database connectivity in python
ODP
Introduction of Html/css/js
PPTX
Basic concepts for python web development
PDF
Ruby on Rails Presentation
PPTX
Arrays in Java
PPTX
Introduction to java
PPTX
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
PPS
Java Exception handling
PPT
PHP - Introduction to Object Oriented Programming with PHP
PPTX
Chapter 05 classes and objects
PPT
Difference between C++ and Java
PPTX
Operator overloading
PPTX
Java constructors
PDF
Control Structures in Python
PDF
Introduction to Java Programming Language
PPT
Object Oriented Design
PPS
Packages and inbuilt classes of java
5. Frames & Forms.pdf
UML Diagrams
Database connectivity in python
Introduction of Html/css/js
Basic concepts for python web development
Ruby on Rails Presentation
Arrays in Java
Introduction to java
Application of Stack For Expression Evaluation by Prakash Zodge DSY 41.pptx
Java Exception handling
PHP - Introduction to Object Oriented Programming with PHP
Chapter 05 classes and objects
Difference between C++ and Java
Operator overloading
Java constructors
Control Structures in Python
Introduction to Java Programming Language
Object Oriented Design
Packages and inbuilt classes of java
Ad

Viewers also liked (9)

Ad

Similar to Stored procedure (20)

PPTX
Procedures and triggers in SQL
PPT
PL/SQL Stored Procedures And Cursors.ppt
PPTX
PPT
Module04
PPT
Lecture 2. MS SQL. Stored procedures.
PPTX
Stored procedures
PPTX
Unit 3(rdbms)
PPTX
Unit 3(rdbms)
PPTX
PLSQL Tutorial
PPT
SQL / PL
PPT
plsql.ppt
PPTX
PL/SQL___________________________________
PPTX
Stored procedures
PDF
Lecture Notes Unit5 chapter 15 PL/SQL Programming
PDF
Bypass dbms assert
PPT
PHP tips by a MYSQL DBA
PDF
Database development coding standards
PPT
PPT
L9 l10 server side programming
Procedures and triggers in SQL
PL/SQL Stored Procedures And Cursors.ppt
Module04
Lecture 2. MS SQL. Stored procedures.
Stored procedures
Unit 3(rdbms)
Unit 3(rdbms)
PLSQL Tutorial
SQL / PL
plsql.ppt
PL/SQL___________________________________
Stored procedures
Lecture Notes Unit5 chapter 15 PL/SQL Programming
Bypass dbms assert
PHP tips by a MYSQL DBA
Database development coding standards
L9 l10 server side programming

More from baabtra.com - No. 1 supplier of quality freshers (20)

PPTX
Agile methodology and scrum development
PDF
Baabtra.com programming at school
PDF
99LMS for Enterprises - LMS that you will love
PPTX
Chapter 6 database normalisation
PPTX
Chapter 5 transactions and dcl statements
PPTX
Chapter 4 functions, views, indexing
PPTX
PPTX
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
PPTX
Chapter 1 introduction to sql server
PPTX
Chapter 1 introduction to sql server
Agile methodology and scrum development
Baabtra.com programming at school
99LMS for Enterprises - LMS that you will love
Chapter 6 database normalisation
Chapter 5 transactions and dcl statements
Chapter 4 functions, views, indexing
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 1 introduction to sql server
Chapter 1 introduction to sql server

Recently uploaded (20)

PDF
Assigned Numbers - 2025 - Bluetooth® Document
PPTX
Tartificialntelligence_presentation.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PDF
Getting Started with Data Integration: FME Form 101
PDF
Unlock new opportunities with location data.pdf
PDF
Five Habits of High-Impact Board Members
PPTX
Chapter 5: Probability Theory and Statistics
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
Hybrid model detection and classification of lung cancer
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
DP Operators-handbook-extract for the Mautical Institute
PDF
Architecture types and enterprise applications.pdf
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PPT
Geologic Time for studying geology for geologist
PPTX
The various Industrial Revolutions .pptx
PPTX
Web Crawler for Trend Tracking Gen Z Insights.pptx
PPTX
observCloud-Native Containerability and monitoring.pptx
PDF
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
PDF
Zenith AI: Advanced Artificial Intelligence
Assigned Numbers - 2025 - Bluetooth® Document
Tartificialntelligence_presentation.pptx
Enhancing emotion recognition model for a student engagement use case through...
Getting Started with Data Integration: FME Form 101
Unlock new opportunities with location data.pdf
Five Habits of High-Impact Board Members
Chapter 5: Probability Theory and Statistics
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Hybrid model detection and classification of lung cancer
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
A novel scalable deep ensemble learning framework for big data classification...
DP Operators-handbook-extract for the Mautical Institute
Architecture types and enterprise applications.pdf
O2C Customer Invoices to Receipt V15A.pptx
Geologic Time for studying geology for geologist
The various Industrial Revolutions .pptx
Web Crawler for Trend Tracking Gen Z Insights.pptx
observCloud-Native Containerability and monitoring.pptx
Hybrid horned lizard optimization algorithm-aquila optimizer for DC motor
Zenith AI: Advanced Artificial Intelligence

Stored procedure

  • 3. What is stored procedure? • A stored procedure is a subroutine available to applications that access a relational database system. • Extensive or complex processing that requires execution of several SQL statements is moved into stored procedures, and all applications call the procedures. • Typical uses for stored procedures include data validation (integrated into the database) or access control mechanisms • stored procedures can consolidate and centralize logic that was originally implemented in applications.
  • 4. Why do we use stored procedures? • stored procedures should run faster -Once created, stored procedures are compiled and stored in the database • saving resources -code is stored in a pre-compiled form ;syntactically valid and does not need to be compiled at run-time • improving the scalability of applications -each user of the stored procedure will use exactly the same form of queries which means the queries are reused One Query Wait, receive, process/compute Database Server Internet
  • 5. • less network traffic -instead of sending multiple lengthy SQL statements, the application has to send only name and parameters of the stored procedure • Stored procedures are secure. - Database administrator can grant appropriate permissions to applications that access stored procedures in the database without giving any permission on the underlying database tables.
  • 6. Disadvantages… • For a lot of stored procedures, the memory usage of every connection will increase substantially. • Overuse a large number of logical operations inside store procedures, the CPU usage will also increase because database server is not well-designed for logical operations. • A constructs of stored procedures make it more difficult to develop stored procedures that have complicated business logic. • It is difficult to debug stored procedures. Only few database management systems allow you to debug stored procedures • It is not easy to develop and maintain stored procedures; Required specialized skill set that not all application developers possess
  • 7. Working with Stored Procedures mysql> CREATE DATABASE db5; Query OK, 1 row affected (0.01 sec) mysql> USE db5; Database changed mysql> CREATE TABLE t (s1 INT); Query OK, 0 rows affected (0.01 sec) mysql> INSERT INTO t VALUES (5); Query OK, 1 row affected (0.00 sec) mysql> DELIMITER //
  • 8. • The delimiter is the character or string of characters that you'll use to tell the mysql client that you've finished typing in an SQL statement CREATE PROCEDURE p1 () SELECT * FROM t; // - Procedure Names are not case sensitive, so 'p1' and 'P1' are the same name. -“() “ is the 'parameter list'. - last part of the statement is the procedure body, which is an SQL statement . -mysql> CALL p1() // Characteristics Clauses:- CREATE PROCEDURE p2 () LANGUAGE SQL <-- the body of the procedure is written in SQL NOT DETERMINISTIC <-- A deterministic procedure is a procedure which will always return the same outputs given the same data inputs SQL SECURITY DEFINER <-- instruction that tells the MySQL server to check the privileges of the user COMMENT 'A Procedure' SELECT CURRENT_DATE, RAND() FROM t //
  • 9. mysql> call p2() // +--------------+-----------------+ | CURRENT_DATE | RAND() | +--------------+-----------------+ | 2004-11-09 | 0.7822275075896 | +--------------+---------- • Parameters :- 1. CREATE PROCEDURE p5 () ... 2. CREATE PROCEDURE p5 ([IN] name data-type) ... 3. CREATE PROCEDURE p5 (OUT name data-type) ... 4. CREATE PROCEDURE p5 (INOUT name data-type)
  • 10. • In the first example the parameter list is empty. • In the second example there is one input parameter. The word IN is optional because parameters are IN (input) by default. • In the third example there is one output parameter. • In the fourth example there is one parameter which is both input and output. IN example:- mysql> CREATE PROCEDURE p5(p INT) SET @x = p // mysql> CALL p5(12345)// mysql> SELECT @x// OUT example:- mysql> CREATE PROCEDURE p6 (OUT p INT) SET p = -5 // mysql> CALL p6(@y)// mysql> SELECT @y//
  • 11. Compound Statements:- • You need a BEGIN/END block whenever you have more than one statement in the procedure • The BEGIN/END block, also called a compound statement, is the place where you can define variables and flow-of-control. The New SQL Statements:- • Variables : The statement you use to define variables in a compound statement is DECLARE. Example with two DECLARE statements CREATE PROCEDURE p8 () BEGIN DECLARE a INT; DECLARE b INT; SET a = 5; SET b = 5; INSERT INTO t VALUES (a); SELECT s1 * a FROM t WHERE s1 >= b; END; //
  • 12. • You don't really define variables within the stored procedure. You define them within the BEGIN/END block • Notice that these variables are not like session variables • You don't start them with an at sign (@). • You must declare them explicitly at the start of the BEGIN/END block, along with their data types. • Once you've declared a variable, you can use it anywhere that you would otherwise use any session variable, or literal, or column name.
  • 13. Example with no DEFAULT clause and SET statement CREATE PROCEDURE p9 () BEGIN DECLARE a INT /* there is no DEFAULT clause */; DECLARE b INT /* there is no DEFAULT clause */; SET a = 5; /* there is a SET statement */ SET b = 5; /* there is a SET statement */ INSERT INTO t VALUES (a); SELECT s1 * a FROM t WHERE s1 >= b; END; // • When declared without a DEFAULT clause, the initial value of a variable is always NULL. • You can use the SET statement to assign another value to a variable at any time.
  • 14. Example with DEFAULT clause CREATE PROCEDURE p10 () BEGIN DECLARE a, b INT DEFAULT 5; INSERT INTO t VALUES (a); SELECT s1 * a FROM t WHERE s1 >= b; END; // • putting both variable declarations on the same line and using a DEFAULT clause to set the initial value, rather than doing two separate DECLARE and SET statements.
  • 15. Scope:- CREATE PROCEDURE p11 () BEGIN DECLARE x1 CHAR(5) DEFAULT 'outer'; BEGIN DECLARE x1 CHAR(5) DEFAULT 'inner'; SELECT x1; END; SELECT x1; END; // mysql> CALL p11()// +-------+ | x1 | +-------+ | inner | +-------+ +-------+ | x1 | +-------+ | outer | +-------+
  • 16. Conditions and IF-THEN-ELSE CREATE PROCEDURE p12 (IN parameter1 INT) BEGIN DECLARE variable1 INT; SET variable1 = parameter1 + 1; IF variable1 = 0 THEN INSERT INTO t VALUES (17); END IF; IF parameter1 = 0 THEN UPDATE t SET s1 = s1 + 1; ELSE UPDATE t SET s1 = s1 + 2; END IF; END; //
  • 17. • The first thing that happens is that variable1 gets set to parameter1 plus one, which means it gets set to zero plus one -- so it will be one. • The next thing that happens is nothing. Since variable1 is one, the condition "if variable1 = 0" isn't true. Therefore everything between the IF and the END IF gets skipped. • So now we go on to the second IF statement. And for this statement, the condition is true, because we know that parameter1 equals zero. That's what we passed. • And since it's true that parameter1 equals zero, this UPDATE is executed. If it had been false, or if parameter1 had been null, the other UPDATE would have been executed instead.
  • 18. CASE:- CREATE PROCEDURE p13 (IN parameter1 INT) BEGIN DECLARE variable1 INT; SET variable1 = parameter1 + 1; CASE variable1 WHEN 0 THEN INSERT INTO t VALUES (17); WHEN 1 THEN INSERT INTO t VALUES (18); ELSE INSERT INTO t VALUES (19); END CASE; END; // mysql> CALL p13(1)//
  • 19. WHILE ... END WHILE:- CREATE PROCEDURE p14 () BEGIN DECLARE v INT; SET v = 0; WHILE v < 5 DO INSERT INTO t VALUES (v); SET v = v + 1; END WHILE; END; // • The INSERT and the SET statements here, which are between the WHILE and the END WHILE, happen over and over until the value in variable v becomes greater than to five.
  • 20. REPEAT ... END REPEAT CREATE PROCEDURE p15 () BEGIN DECLARE v INT; SET v = 0; REPEAT INSERT INTO t VALUES (v); SET v = v + 1; UNTIL v >= 5 END REPEAT; END; // • Note that there is no semicolon after the UNTIL clause in this procedure statement.
  • 21. LOOP ... END LOOP CREATE PROCEDURE p16 () BEGIN DECLARE v INT; SET v = 0; loop_label: LOOP INSERT INTO t VALUES (v); SET v = v + 1; IF v >= 5 THEN LEAVE loop_label; END IF; END LOOP; END; // • The LEAVE statement means "exit the loop". The actual syntax of the LEAVE statement is the word LEAVE and a statement label.
  • 22. Error Handling:- Sample Problem: Log Of Failures mysql> CREATE TABLE t2 s1 INT, PRIMARY KEY (s1)) // mysql> CREATE TABLE t3 (s1 INT, KEY (s1), FOREIGN KEY (s1) REFERENCES t2 (s1)) // mysql> INSERT INTO t3 VALUES (5);// ... ERROR 1216 (23000): Cannot add or update a child row: a foreign key constraint fails CREATE TABLE error_log (error_message CHAR(80))// < -- create error log
  • 23. Exit handler:- CREATE PROCEDURE p22 (parameter1 INT) BEGIN DECLARE EXIT HANDLER FOR 1216 INSERT INTO error_log VALUES (CONCAT('Time: ',current_date, ‘ Foreign Key Reference Failure For Value = ',parameter1)); INSERT INTO t3 VALUES (parameter1); END;// • The word EXIT means "we'll exit from the compound statement when we're done".
  • 24. Declare continue handler example :- CREATE TABLE t4 (s1 int,primary key(s1));// CREATE PROCEDURE p23 () BEGIN DECLARE CONTINUE HANDLER FOR SQLSTATE '23000' SET @x2 = 1; SET @x = 1; <-- start execution INSERT INTO t4 VALUES (1); SET @x = 2; INSERT INTO t4 VALUES (1); SET @x = 3; END;//
  • 25. Declare condition :- CREATE PROCEDURE p24 () BEGIN DECLARE `Constraint Violation` CONDITION FOR SQLSTATE '23000'; DECLARE EXIT HANDLER FOR `Constraint Violation` ROLLBACK; START TRANSACTION; INSERT INTO t2 VALUES (1); INSERT INTO t2 VALUES (1); COMMIT; END; // • give the SQLSTATE or the error code another name. And then you can use that name in a handler
  • 26. Cursors:- drop procedure if exists p25// CREATE PROCEDURE p25 (OUT return_val INT) BEGIN DECLARE a,c text; DECLARE b int; DECLARE cur_1 CURSOR FOR SELECT flightno,details FROM tbl_flight; DECLARE CONTINUE HANDLER FOR NOT FOUND SET b = 1; OPEN cur_1; REPEAT FETCH cur_1 INTO a; UNTIL b = 1 END REPEAT; CLOSE cur_1; SET return_val = a; END;//
  • 27. • order is important. First declare variables. Then declare conditions. Then declare cursors. Then, declare handlers. If you put them in the wrong order, you will get an error message. • The first FETCH statement here will cause a single row to be retrieved from the result set that the SELECT produced. Since we know that there are several rows in table t, we know that this statement will happen several times -- that is, it is in a loop.
  • 28. Cursor Characteristics:- • read only • not scrollable • Asensitive READ ONLY -Can not say FETCH cursor1 INTO variable1; UPDATE t1 SET column1 = 'value1' WHERE CURRENT OF cursor1; NOT SCROLLABLE FETCH PRIOR cursor1 INTO variable1; FETCH ABSOLUTE 55 cursor1 INTO variable1; • And you should avoid doing updates on a table while you have a cursor open on the same table, because cursors are asensitive.
  • 30. If this presentation helped you, please visit our page facebook.com/baabtra and like it. Thanks in advance. www.baabtra.com | www.massbaab.com |www.baabte.com
  • 31. Contact Us Emarald Mall (Big Bazar Building) Mavoor Road, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 NC Complex, Near Bus Stand Mukkam, Kozhikode, Kerala, India. Ph: + 91 – 495 40 25 550 Start up Village Eranakulam, Kerala, India. Email: info@baabtra.com

Editor's Notes

  • #5: The main speed gain comes from reduction of network traffic. If you have a repetitive task that requires checking, looping, multiple statements, and no user interaction, do it with a single call to a procedure that&apos;s stored on the server.