SlideShare a Scribd company logo
1 of 31
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

What's hot

T sql denali code Day of .Net
T sql denali code Day of .NetT sql denali code Day of .Net
T sql denali code Day of .NetKathiK58
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveNaresha K
 
Oracle 11g new features for developers
Oracle 11g new features for developersOracle 11g new features for developers
Oracle 11g new features for developersScott Wesley
 
Meet MariaDB 10.3 Debconf 2017
Meet MariaDB 10.3   Debconf 2017Meet MariaDB 10.3   Debconf 2017
Meet MariaDB 10.3 Debconf 2017Vicentiu Ciorbaru
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Thuan Nguyen
 
The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84Mahmoud Samir Fayed
 
C++ control structure
C++ control structureC++ control structure
C++ control structurebluejayjunior
 
Les23[1]Handling Exceptions
Les23[1]Handling ExceptionsLes23[1]Handling Exceptions
Les23[1]Handling Exceptionssiavosh kaviani
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in ApexJeffrey Kemp
 

What's hot (20)

T sql denali code Day of .Net
T sql denali code Day of .NetT sql denali code Day of .Net
T sql denali code Day of .Net
 
Sql triggers
Sql triggersSql triggers
Sql triggers
 
Module04
Module04Module04
Module04
 
PL/SQL
PL/SQLPL/SQL
PL/SQL
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
 
Oracle 11g new features for developers
Oracle 11g new features for developersOracle 11g new features for developers
Oracle 11g new features for developers
 
Meet MariaDB 10.3 Debconf 2017
Meet MariaDB 10.3   Debconf 2017Meet MariaDB 10.3   Debconf 2017
Meet MariaDB 10.3 Debconf 2017
 
PLSQL Cursors
PLSQL CursorsPLSQL Cursors
PLSQL Cursors
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 
Introduction to sql_02
Introduction to sql_02Introduction to sql_02
Introduction to sql_02
 
The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84The Ring programming language version 1.2 book - Part 58 of 84
The Ring programming language version 1.2 book - Part 58 of 84
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Pl sql using_xml
Pl sql using_xmlPl sql using_xml
Pl sql using_xml
 
C++ control structure
C++ control structureC++ control structure
C++ control structure
 
Les23[1]Handling Exceptions
Les23[1]Handling ExceptionsLes23[1]Handling Exceptions
Les23[1]Handling Exceptions
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in Apex
 
stack
stackstack
stack
 
Function
FunctionFunction
Function
 

Viewers also liked (6)

.Net framework
.Net framework.Net framework
.Net framework
 
Intoduction to php restful web service
Intoduction to php  restful web serviceIntoduction to php  restful web service
Intoduction to php restful web service
 
Memory
MemoryMemory
Memory
 
function Creation in Mysql
function Creation in Mysqlfunction Creation in Mysql
function Creation in Mysql
 
Header creation in CPP
Header creation in CPPHeader creation in CPP
Header creation in CPP
 
Normalization
NormalizationNormalization
Normalization
 

Similar to Stored Procedure Overview

Similar to Stored Procedure Overview (20)

Procedures and triggers in SQL
Procedures and triggers in SQLProcedures and triggers in SQL
Procedures and triggers in SQL
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
Lecture 2. MS SQL. Stored procedures.
Lecture 2. MS SQL. Stored procedures.Lecture 2. MS SQL. Stored procedures.
Lecture 2. MS SQL. Stored procedures.
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
SQL / PL
SQL / PLSQL / PL
SQL / PL
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
plsql.ppt
plsql.pptplsql.ppt
plsql.ppt
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Bypass dbms assert
Bypass dbms assertBypass dbms assert
Bypass dbms assert
 
PHP tips by a MYSQL DBA
PHP tips by a MYSQL DBAPHP tips by a MYSQL DBA
PHP tips by a MYSQL DBA
 
Database development coding standards
Database development coding standardsDatabase development coding standards
Database development coding standards
 
stored.ppt
stored.pptstored.ppt
stored.ppt
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 
Subqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactionsSubqueries views stored procedures_triggers_transactions
Subqueries views stored procedures_triggers_transactions
 
Performance tuning
Performance tuningPerformance tuning
Performance tuning
 
MySQL Stored Procedures: Building High Performance Web Applications
MySQL Stored Procedures: Building High Performance Web ApplicationsMySQL Stored Procedures: Building High Performance Web Applications
MySQL Stored Procedures: Building High Performance Web Applications
 
Chapter 3 stored procedures
Chapter 3 stored proceduresChapter 3 stored procedures
Chapter 3 stored procedures
 
05 Creating Stored Procedures
05 Creating Stored Procedures05 Creating Stored Procedures
05 Creating Stored Procedures
 

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

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

Agile methodology and scrum development
Agile methodology and scrum developmentAgile methodology and scrum development
Agile methodology and scrum development
 
Best coding practices
Best coding practicesBest coding practices
Best coding practices
 
Core java - baabtra
Core java - baabtraCore java - baabtra
Core java - baabtra
 
Acquiring new skills what you should know
Acquiring new skills   what you should knowAcquiring new skills   what you should know
Acquiring new skills what you should know
 
Baabtra.com programming at school
Baabtra.com programming at schoolBaabtra.com programming at school
Baabtra.com programming at school
 
99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love 99LMS for Enterprises - LMS that you will love
99LMS for Enterprises - LMS that you will love
 
Php sessions & cookies
Php sessions & cookiesPhp sessions & cookies
Php sessions & cookies
 
Php database connectivity
Php database connectivityPhp database connectivity
Php database connectivity
 
Chapter 6 database normalisation
Chapter 6  database normalisationChapter 6  database normalisation
Chapter 6 database normalisation
 
Chapter 5 transactions and dcl statements
Chapter 5  transactions and dcl statementsChapter 5  transactions and dcl statements
Chapter 5 transactions and dcl statements
 
Chapter 4 functions, views, indexing
Chapter 4  functions, views, indexingChapter 4  functions, views, indexing
Chapter 4 functions, views, indexing
 
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
Chapter 2  grouping,scalar and aggergate functions,joins   inner join,outer joinChapter 2  grouping,scalar and aggergate functions,joins   inner join,outer join
Chapter 2 grouping,scalar and aggergate functions,joins inner join,outer join
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Chapter 1 introduction to sql server
Chapter 1 introduction to sql serverChapter 1 introduction to sql server
Chapter 1 introduction to sql server
 
Microsoft holo lens
Microsoft holo lensMicrosoft holo lens
Microsoft holo lens
 
Blue brain
Blue brainBlue brain
Blue brain
 
5g
5g5g
5g
 
Aptitude skills baabtra
Aptitude skills baabtraAptitude skills baabtra
Aptitude skills baabtra
 
Gd baabtra
Gd baabtraGd baabtra
Gd baabtra
 
Baabtra soft skills
Baabtra soft skillsBaabtra soft skills
Baabtra soft skills
 

Recently uploaded

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Recently uploaded (20)

GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

Stored Procedure Overview

  • 1.
  • 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

  1. 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.