SlideShare a Scribd company logo
1 of 26
STORED PROCEDURE
STORED PROCEDURE
RAJISHMA T.
19/04/89
• A Stored procedure is a procedure that is stored in
a database.
• It has a name,parameter list and sql statements.
• The first part of the SQL statement that creates a
stored procedure is the words "CREATE
PROCEDURE".
• CREATE PROCEDURE p1 () SELECT * FROM t; /
• The second part is the procedure name. The name
of this new procedure will be p1
• My sql statements are legal in the body of a stored
procedure.
• We cant put database manipulation statements that
manipulate a routine such as create
procedure,create function,drop function,drop
procedure,alter procedure etc etc.
• Statements like use database are also illegal.
• Call the procedure
 To call a procedure we use the call
keyword and then the procedure name
and paranthesis.
Eg:call p1();
ADVANTAGES:
• Stored procedure increases performance of
application.
• Stored procedure reduced the traffic between
application and database server.
• Stored procedure is reusable and transparent
to any application which wants to use it.
• Stored procedure is secured.
CHARACTERESTIC CLAUSES
• There is some clauses which describes the characterestics
of the procedure.
• Consider the eg below with charactarestics clauses.
• Create procedure p2()
language SQL
not deterministic
SQL security defines
comment ‘a procedure’
select * from t
VARIABLES
 the statements used to define variables in a compount
statement is declare.
 Eg: declare a int;
 Variables are declared between the begin and end tag.
 Scope of the variable:
CREATE PROCEDURE p()
BEGIN
DECLARE x1 CHAR(5) DEFAULT 'outer';
BEGIN
DECLARE x1 CHAR(5) DEFAULT 'inner';
SELECT x1;
END;
SELECT x1;
END;
Call scope example: call p()
X1
inner
x1
outer
PARAMETERS
• 1. CREATE PROCEDURE p() ...
• 2. CREATE PROCEDURE p([IN] name data-type)
...
• 3. CREATE PROCEDURE p(OUT name data-
type) ...
• 4. CREATE PROCEDURE p(INOUT name data-
type)
IN EG:
Delimiter //
create procedure p1(in p int)
Begin
declare x int;
Set x = p ;
Select x;
End //
Call p(123);
OUT EG:
CREATE PROCEDURE p2 (OUT p INT)
Begin
SET p = -5;
select p;
End //
Call p2(@o)
INOUT EG:
CREATE PROCEDURE P3(INOUT P INT)
BEGIN
SET P=P*2;
Select p;
END //
Set @y=5;
Call p3(@y);
IF-THEN -ELSE
CREATE PROCEDURE p3(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
INSERT INTO T VALUES(15);
ELSE
INSERT INTO T VALUES(15);
END IF;
END; //
CASE:
CREATE PROCEDURE p4(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; //
WHILE------END WHILE
CREATE PROCEDURE p5 ()
BEGIN
DECLARE v INT;
SET v = 0;
WHILE v < 5 DO
INSERT INTO t VALUES (v);
SET v = v + 1;
END WHILE;
END; //
REPEAT------END REPEAT
CREATE PROCEDURE p6 ()
BEGIN
DECLARE v INT;
SET v = 0;
REPEAT
INSERT INTO t VALUES (v);
SET v = v + 1;
UNTIL v >= 5
END REPEAT;
END; //
LOOP-------END LOOP
CREATE PROCEDURE p7 ()
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; //
GO TO:
CREATE PROCEDURE p...
BEGIN
...............
LABEL label_name;
...............
GOTO label_name;
...............
END
ERROR HANDLNG
• SYNTAX:
DECLARE
{ EXIT | CONTINUE }
HANDLER FOR
{ error-number | { SQLSTATE error-string } | condition }
SQL statement
EXIT HANDLER EG:
Create procedure department_ex(in dept_name varchar(30),in
dept_location varchar(30),in id int)
Begin
declare d_key int default 0;
Begin
declare exit handler for 1062 set d_key=1;
insert into departments
values(dept_name,dept_location,id);
select concat (‘department’,dept_name,’created successfully’) as
“result”;
end;
If d_key=1 then
select concat(‘failed to insert’,dept_name,’:duplicate key’) as
“result”;
End if
End //
CONTINUE HANDLER EG:
Create procedure department_co(in dept_name varchar(30),in dept_location varchar(30),in
id int)
Begin
declare d_key int default 0;
declare exit handler for 1062
begin
set d_key=1;
End;
insert into departments
values(dept_name,dept_location,id);
If d_key=1 then
select concat(‘failed to insert’,dept_name,’:duplicate key’) as
“result”;
else
select concat (‘department’dept_name,’created successfully’) as
“result”;
End if
End //
CONDITION:
Declare no_such_table condition for sqlstate
42S02
Declare continue handler for no_such_table
Begin
------body of handler-------
End //
CURSORS:
• In sql procedure a cursor make it possible to define a result
set (a set of data rows) and perform complex logic on a row by
row basis.
• To use cursors in SQL procedures, need to do the following:
1:Declare a cursor that defines a result.
2:Open the cursor to establish the result set.
3:Fetch the data into local variables as needed
from the cursor, one row at a time.
4:Close the cursor when done
To work with cursors you must use the following
SQL statements:
• DECLARE cursor-name CURSOR FOR SELECT ...;
• OPEN cursor-name;
• FETCH cursor-name INTO variable [, variable];
• CLOSE cursor-name;
CURSOR EG:
CREATE PROCEDURE p()
BEGIN
DECLARE id INT;
DECLARE cur_1 CURSOR FOR SELECT i FROM
departments;
OPEN cur_1;
FETCH cur_1 INTO id;
set id=id*2
select id;
CLOSE cur_1;
END;//
Thank you

More Related Content

What's hot (20)

Joins in SQL
Joins in SQLJoins in SQL
Joins in SQL
 
Database Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and deleteDatabase Management - Lecture 2 - SQL select, insert, update and delete
Database Management - Lecture 2 - SQL select, insert, update and delete
 
SQL - Structured query language introduction
SQL - Structured query language introductionSQL - Structured query language introduction
SQL - Structured query language introduction
 
SQL Queries Information
SQL Queries InformationSQL Queries Information
SQL Queries Information
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Oracle Database Sequence
Oracle Database SequenceOracle Database Sequence
Oracle Database Sequence
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | Edureka
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Oracle SQL Basics
Oracle SQL BasicsOracle SQL Basics
Oracle SQL Basics
 
Sql views
Sql viewsSql views
Sql views
 
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with ExamplesDML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
DML, DDL, DCL ,DRL/DQL and TCL Statements in SQL with Examples
 
Sql server T-sql basics ppt-3
Sql server T-sql basics  ppt-3Sql server T-sql basics  ppt-3
Sql server T-sql basics ppt-3
 
Trigger in mysql
Trigger in mysqlTrigger in mysql
Trigger in mysql
 
Sql dml & tcl 2
Sql   dml & tcl 2Sql   dml & tcl 2
Sql dml & tcl 2
 
PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts PL/SQL Introduction and Concepts
PL/SQL Introduction and Concepts
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
Packages in PL/SQL
Packages in PL/SQLPackages in PL/SQL
Packages in PL/SQL
 
Basic sql Commands
Basic sql CommandsBasic sql Commands
Basic sql Commands
 
SQL Joins and Query Optimization
SQL Joins and Query OptimizationSQL Joins and Query Optimization
SQL Joins and Query Optimization
 

Similar to Stored procedure (20)

SAP Batch data communication
SAP Batch data communicationSAP Batch data communication
SAP Batch data communication
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09Oracle - Program with PL/SQL - Lession 09
Oracle - Program with PL/SQL - Lession 09
 
How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012How to tune a query - ODTUG 2012
How to tune a query - ODTUG 2012
 
Module04
Module04Module04
Module04
 
Stored procedures
Stored proceduresStored procedures
Stored procedures
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Unit 3(rdbms)
Unit 3(rdbms)Unit 3(rdbms)
Unit 3(rdbms)
 
Sap scripts
Sap scriptsSap scripts
Sap scripts
 
Add an interactive command line to your C++ application
Add an interactive command line to your C++ applicationAdd an interactive command line to your C++ application
Add an interactive command line to your C++ application
 
report
reportreport
report
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.Découvrir dtrace en ligne de commande.
Découvrir dtrace en ligne de commande.
 
How to transfer bad PLSQL into good (AAAPEKS23)
How to transfer bad PLSQL into good (AAAPEKS23)How to transfer bad PLSQL into good (AAAPEKS23)
How to transfer bad PLSQL into good (AAAPEKS23)
 
An Overview of SystemVerilog for Design and Verification
An Overview of SystemVerilog  for Design and VerificationAn Overview of SystemVerilog  for Design and Verification
An Overview of SystemVerilog for Design and Verification
 
What's in a name
What's in a nameWhat's in a name
What's in a name
 
Eff Plsql
Eff PlsqlEff Plsql
Eff Plsql
 
Pdxpugday2010 pg90
Pdxpugday2010 pg90Pdxpugday2010 pg90
Pdxpugday2010 pg90
 

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

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 

Stored procedure

  • 3. • A Stored procedure is a procedure that is stored in a database. • It has a name,parameter list and sql statements. • The first part of the SQL statement that creates a stored procedure is the words "CREATE PROCEDURE". • CREATE PROCEDURE p1 () SELECT * FROM t; / • The second part is the procedure name. The name of this new procedure will be p1 • My sql statements are legal in the body of a stored procedure.
  • 4. • We cant put database manipulation statements that manipulate a routine such as create procedure,create function,drop function,drop procedure,alter procedure etc etc. • Statements like use database are also illegal. • Call the procedure  To call a procedure we use the call keyword and then the procedure name and paranthesis. Eg:call p1();
  • 5. ADVANTAGES: • Stored procedure increases performance of application. • Stored procedure reduced the traffic between application and database server. • Stored procedure is reusable and transparent to any application which wants to use it. • Stored procedure is secured.
  • 6. CHARACTERESTIC CLAUSES • There is some clauses which describes the characterestics of the procedure. • Consider the eg below with charactarestics clauses. • Create procedure p2() language SQL not deterministic SQL security defines comment ‘a procedure’ select * from t
  • 7. VARIABLES  the statements used to define variables in a compount statement is declare.  Eg: declare a int;  Variables are declared between the begin and end tag.  Scope of the variable: CREATE PROCEDURE p() BEGIN DECLARE x1 CHAR(5) DEFAULT 'outer'; BEGIN DECLARE x1 CHAR(5) DEFAULT 'inner'; SELECT x1; END; SELECT x1; END;
  • 8. Call scope example: call p() X1 inner x1 outer
  • 9. PARAMETERS • 1. CREATE PROCEDURE p() ... • 2. CREATE PROCEDURE p([IN] name data-type) ... • 3. CREATE PROCEDURE p(OUT name data- type) ... • 4. CREATE PROCEDURE p(INOUT name data- type)
  • 10. IN EG: Delimiter // create procedure p1(in p int) Begin declare x int; Set x = p ; Select x; End // Call p(123);
  • 11. OUT EG: CREATE PROCEDURE p2 (OUT p INT) Begin SET p = -5; select p; End // Call p2(@o)
  • 12. INOUT EG: CREATE PROCEDURE P3(INOUT P INT) BEGIN SET P=P*2; Select p; END // Set @y=5; Call p3(@y);
  • 13. IF-THEN -ELSE CREATE PROCEDURE p3(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 INSERT INTO T VALUES(15); ELSE INSERT INTO T VALUES(15); END IF; END; //
  • 14. CASE: CREATE PROCEDURE p4(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; //
  • 15. WHILE------END WHILE CREATE PROCEDURE p5 () BEGIN DECLARE v INT; SET v = 0; WHILE v < 5 DO INSERT INTO t VALUES (v); SET v = v + 1; END WHILE; END; //
  • 16. REPEAT------END REPEAT CREATE PROCEDURE p6 () BEGIN DECLARE v INT; SET v = 0; REPEAT INSERT INTO t VALUES (v); SET v = v + 1; UNTIL v >= 5 END REPEAT; END; //
  • 17. LOOP-------END LOOP CREATE PROCEDURE p7 () 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; //
  • 18. GO TO: CREATE PROCEDURE p... BEGIN ............... LABEL label_name; ............... GOTO label_name; ............... END
  • 19. ERROR HANDLNG • SYNTAX: DECLARE { EXIT | CONTINUE } HANDLER FOR { error-number | { SQLSTATE error-string } | condition } SQL statement
  • 20. EXIT HANDLER EG: Create procedure department_ex(in dept_name varchar(30),in dept_location varchar(30),in id int) Begin declare d_key int default 0; Begin declare exit handler for 1062 set d_key=1; insert into departments values(dept_name,dept_location,id); select concat (‘department’,dept_name,’created successfully’) as “result”; end; If d_key=1 then select concat(‘failed to insert’,dept_name,’:duplicate key’) as “result”; End if End //
  • 21. CONTINUE HANDLER EG: Create procedure department_co(in dept_name varchar(30),in dept_location varchar(30),in id int) Begin declare d_key int default 0; declare exit handler for 1062 begin set d_key=1; End; insert into departments values(dept_name,dept_location,id); If d_key=1 then select concat(‘failed to insert’,dept_name,’:duplicate key’) as “result”; else select concat (‘department’dept_name,’created successfully’) as “result”; End if End //
  • 22. CONDITION: Declare no_such_table condition for sqlstate 42S02 Declare continue handler for no_such_table Begin ------body of handler------- End //
  • 23. CURSORS: • In sql procedure a cursor make it possible to define a result set (a set of data rows) and perform complex logic on a row by row basis. • To use cursors in SQL procedures, need to do the following: 1:Declare a cursor that defines a result. 2:Open the cursor to establish the result set. 3:Fetch the data into local variables as needed from the cursor, one row at a time. 4:Close the cursor when done
  • 24. To work with cursors you must use the following SQL statements: • DECLARE cursor-name CURSOR FOR SELECT ...; • OPEN cursor-name; • FETCH cursor-name INTO variable [, variable]; • CLOSE cursor-name;
  • 25. CURSOR EG: CREATE PROCEDURE p() BEGIN DECLARE id INT; DECLARE cur_1 CURSOR FOR SELECT i FROM departments; OPEN cur_1; FETCH cur_1 INTO id; set id=id*2 select id; CLOSE cur_1; END;//