SlideShare a Scribd company logo
STORED PROCEDURE
Introduction to MySQL CREATE PROCEDURE statement
The stored procedure is SQL statements wrapped within
the CREATE PROCEDURE statement.
To create a stored procedure, you use the CREATE PROCEDURE
statement.
Basic syntax of the CREATE PROCEDURE statement:
CREATE PROCEDURE sp_name(parameter_list)
BEGIN
statements;
END;
In this syntax:
• First, define the name of the stored procedure sp_name after the
CREATE PROCEDURE keywords.
• Second, specify the parameter list (parameter_list) inside the
parentheses followed by the stored procedure’s name. If the stored
procedure has no parameters, you can use an empty parentheses ().
• Third, write the stored procedure body that consists of one or more
valid SQL statements between the BEGIN and END block.
If you attempt to create a stored procedure that already exists, MySQL
will issue an error.
To prevent the error, you can add an additional clause IF NOT EXISTS
after the CREATE PROCEDURE keywords:
CREATE PROCEDURE [IF NOT EXISTS] sp_name
([parameter[,...]]) routine_body;
The following SELECT statement returns all rows in the table customers
from the sample database:
SELECT
customerName,
city,
state,
postalCode,
country
FROM
customers
ORDER BY customerName;
STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk
If you intend to save this query on the database server for later
execution, one way to achieve this is by using a stored procedure.
The following CREATE PROCEDURE statement creates a new stored
procedure encapsulating the query above:
DELIMITER $$
CREATE PROCEDURE GetCustomers()
BEGIN
SELECT
customerName,
city,
state,
postalCode,
country
FROM
customers
ORDER BY customerName;
END$$
DELIMITER ;
A stored procedure is a set of declarative SQL statements stored within
the MySQL Server. In this example, we have just created a stored
procedure named GetCustomers().
After saving the stored procedure, you can invoke it by using the CALL
statement:
CALL GetCustomers();
The statement returns the same result as the query.
The initial invocation of a stored procedure involves the following
actions by MySQL:
• First, find the stored procedure by its name in the database catalog.
• Second, compile the code of the stored procedure.
• Third, store the compiled stored procedure in a cache memory area.
• Finally, execute the stored procedure.
MySQL Stored Procedures advantages
• Reduce network traffic – Stored procedures help reduce the network
traffic between applications and MySQL servers. Instead of sending
multiple lengthy SQL statements, applications only need to send the name
and parameters of the stored procedures.
• Centralize business logic in the database – You can use stored procedures
to implement reusable business logic across multiple applications. They
streamline the process, reducing the need to duplicate the same logic in
multiple applications and contributing a more consistent database.
• Make the database more secure – You can grant specific privileges to
applications, allowing access to particular stored procedures without
providing any privileges to the underlying tables.
MySQL stored procedures
disadvantages
• Resource usage – If you use many stored procedures, the memory usage of
every connection will significantly increase. Additionally, an excessive use of
logical operations in the stored procedures can lead to increased CPU usage, as
MySQL is not well-designed for such operations.
• Troubleshooting – Debugging stored procedures is quite challenging.
Unfortunately, MySQL lacks facilities for debugging stored procedures, a
feature available in other enterprise database products such as Oracle
Database and SQL Server.
• Maintenances – Developing and maintaining stored procedures often demands
a specialized skill set not universally possessed by all application developers,
potentially causing issues in both application development and maintenance.
Simple stored procedure
DELIMITER //
CREATE PROCEDURE GetEmployeeCount()
BEGIN
SELECT COUNT(*) AS employee_count FROM employees;
END//
DELIMITER ;
This stored procedure simply returns the count of employees from the employees
table.
Stored Procedure with Parameters
DELIMITER //
CREATE PROCEDURE GetEmployeeByDepartment(IN dept_id INT)
BEGIN
SELECT * FROM employees WHERE department_id = dept_id;
END//
DELIMITER ;
This stored procedure takes a department ID as input parameter and returns all
employees belonging to that department.
Stored Procedure with Output
Parameters
DELIMITER //
CREATE PROCEDURE GetDepartmentCount(OUT dept_count INT)
BEGIN
SELECT COUNT(*) INTO dept_count FROM departments;
END//
DELIMITER ;
This stored procedure calculates the count of departments and returns it via an output
parameter.
Stored Procedure with Conditional
Logic:
DELIMITER //
CREATE PROCEDURE GetHighSalaryEmployees()
BEGIN
DECLARE min_salary DECIMAL(10, 2);
SET min_salary = 50000;
SELECT * FROM employees WHERE salary >= min_salary;
END//
DELIMITER ;
This stored procedure retrieves employees with salaries equal to or higher than a specified
threshold.
To call these stored procedures, you can use the CALL statement
followed by the procedure name and any necessary parameters.
For example:
CALL GetEmployeeCount();
How to execute stored procedure
1. Open MySQL Workbench
2. Create New tab to run SQL statements.
3. Enter the SQL statements for stored procedure in your new tab.
4. Execute the store procedure statements by clicking the ‘lightning’
icon shown below. That will call stored procedure in MySQL
Workbench.
5. Expand the stored procedure node in right pane. You
should see the name of your stored procedure (get_products).
If you don’t see it, then hit refresh button next to SCHEMAS
Drop a Stored Procedure
You can use the MySQL
workbench wizard to drop
the procedure. To drop any
procedure, expand sakila
schema Expand Stored
Procedures Right-click on
sp_GetMovies Click on
Drop Stored Procedure.
To drop the stored procedure, you can use the drop procedure command. The syntax is
following
Drop procedure [IF EXISTS] <Procedure Name>
In the syntax, the name of the stored procedure must be followed by the Drop Procedure
keyword. If you want to drop the sp_getCustomers procedure from the sakila database, you can
run the following query.
Drop procedure sp_getCustomers
When you try to drop the procedure that does not exist on a database, the query shows an error:
ERROR 1305 (42000): PROCEDURE sakila.getCustomer does not exist
To avoid this, you can include the [IF EXISTS] option in the drop procedure command. When you
include the IF EXISTS keyword, instead of an error, the query returns a warning:
How to
modify
stored
procedure
How to
modify
stored
procedure
Summary
• A stored procedure is a wrapper of a set of SQL statements stored in the
MySQL database server.
• The advantages of stored procedures include reduced network traffic,
enhanced code reusability, improved security through controlled access,
streamlined implementation of business logic, and the ability to grant
specific privileges to applications without exposing underlying database
structures.
• The disadvantages of stored procedures include increased memory usage
for each connection, challenges in debugging due to a lack of dedicated
tools, and the necessity for a specialized skill set, which not all application
developers may possess, leading to potential difficulties in both
development and maintenance processes.

More Related Content

PPTX
Getting Started with MySQL II
PPTX
Sql storeprocedure
PPT
Intro to tsql
PPT
Intro to tsql unit 14
PPTX
Store procedures
PPTX
Procedures and triggers in SQL
PPTX
Advance Sql Server Store procedure Presentation
Getting Started with MySQL II
Sql storeprocedure
Intro to tsql
Intro to tsql unit 14
Store procedures
Procedures and triggers in SQL
Advance Sql Server Store procedure Presentation

Similar to STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk (20)

PPTX
05_DP_300T00A_Optimize.pptx
ODP
SQL Tunning
PPTX
PDF
Stored procedure Notes By Durgesh Singh
PPTX
DOC
Subqueries views stored procedures_triggers_transactions
PPTX
Stored procedures by thanveer danish melayi
PPS
Procedures/functions of rdbms
PPT
Acutate - Using Stored Procedure
PPTX
Data Redaction - OTN TOUR LA 2015
PPTX
Oracle: Procedures
PPTX
Oracle: Procedures
PPTX
Stored procedures
PPTX
MySQL Performance Schema : fossasia
PPTX
Sql and PL/SQL Best Practices I
PPT
lecture13.ppt
PPTX
Oracle Data Redaction
PPT
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
ODP
Performance tuning
PPTX
DBA Commands and Concepts That Every Developer Should Know - Part 2
05_DP_300T00A_Optimize.pptx
SQL Tunning
Stored procedure Notes By Durgesh Singh
Subqueries views stored procedures_triggers_transactions
Stored procedures by thanveer danish melayi
Procedures/functions of rdbms
Acutate - Using Stored Procedure
Data Redaction - OTN TOUR LA 2015
Oracle: Procedures
Oracle: Procedures
Stored procedures
MySQL Performance Schema : fossasia
Sql and PL/SQL Best Practices I
lecture13.ppt
Oracle Data Redaction
Tony jambu (obscure) tools of the trade for tuning oracle sq ls
Performance tuning
DBA Commands and Concepts That Every Developer Should Know - Part 2
Ad

Recently uploaded (20)

PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
master seminar digital applications in india
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Complications of Minimal Access Surgery at WLH
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Institutional Correction lecture only . . .
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Basic Mud Logging Guide for educational purpose
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
RMMM.pdf make it easy to upload and study
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
Pre independence Education in Inndia.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
O7-L3 Supply Chain Operations - ICLT Program
master seminar digital applications in india
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
Microbial diseases, their pathogenesis and prophylaxis
Week 4 Term 3 Study Techniques revisited.pptx
Complications of Minimal Access Surgery at WLH
Insiders guide to clinical Medicine.pdf
Institutional Correction lecture only . . .
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Basic Mud Logging Guide for educational purpose
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
RMMM.pdf make it easy to upload and study
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Pre independence Education in Inndia.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Ad

STORED-PROCEDURE.pptxjsjjdjdjcjcjdkksksksk

  • 2. Introduction to MySQL CREATE PROCEDURE statement The stored procedure is SQL statements wrapped within the CREATE PROCEDURE statement. To create a stored procedure, you use the CREATE PROCEDURE statement. Basic syntax of the CREATE PROCEDURE statement: CREATE PROCEDURE sp_name(parameter_list) BEGIN statements; END;
  • 3. In this syntax: • First, define the name of the stored procedure sp_name after the CREATE PROCEDURE keywords. • Second, specify the parameter list (parameter_list) inside the parentheses followed by the stored procedure’s name. If the stored procedure has no parameters, you can use an empty parentheses (). • Third, write the stored procedure body that consists of one or more valid SQL statements between the BEGIN and END block.
  • 4. If you attempt to create a stored procedure that already exists, MySQL will issue an error. To prevent the error, you can add an additional clause IF NOT EXISTS after the CREATE PROCEDURE keywords: CREATE PROCEDURE [IF NOT EXISTS] sp_name ([parameter[,...]]) routine_body;
  • 5. The following SELECT statement returns all rows in the table customers from the sample database: SELECT customerName, city, state, postalCode, country FROM customers ORDER BY customerName;
  • 7. If you intend to save this query on the database server for later execution, one way to achieve this is by using a stored procedure. The following CREATE PROCEDURE statement creates a new stored procedure encapsulating the query above:
  • 8. DELIMITER $$ CREATE PROCEDURE GetCustomers() BEGIN SELECT customerName, city, state, postalCode, country FROM customers ORDER BY customerName; END$$ DELIMITER ;
  • 9. A stored procedure is a set of declarative SQL statements stored within the MySQL Server. In this example, we have just created a stored procedure named GetCustomers(). After saving the stored procedure, you can invoke it by using the CALL statement: CALL GetCustomers();
  • 10. The statement returns the same result as the query. The initial invocation of a stored procedure involves the following actions by MySQL: • First, find the stored procedure by its name in the database catalog. • Second, compile the code of the stored procedure. • Third, store the compiled stored procedure in a cache memory area. • Finally, execute the stored procedure.
  • 11. MySQL Stored Procedures advantages • Reduce network traffic – Stored procedures help reduce the network traffic between applications and MySQL servers. Instead of sending multiple lengthy SQL statements, applications only need to send the name and parameters of the stored procedures. • Centralize business logic in the database – You can use stored procedures to implement reusable business logic across multiple applications. They streamline the process, reducing the need to duplicate the same logic in multiple applications and contributing a more consistent database. • Make the database more secure – You can grant specific privileges to applications, allowing access to particular stored procedures without providing any privileges to the underlying tables.
  • 12. MySQL stored procedures disadvantages • Resource usage – If you use many stored procedures, the memory usage of every connection will significantly increase. Additionally, an excessive use of logical operations in the stored procedures can lead to increased CPU usage, as MySQL is not well-designed for such operations. • Troubleshooting – Debugging stored procedures is quite challenging. Unfortunately, MySQL lacks facilities for debugging stored procedures, a feature available in other enterprise database products such as Oracle Database and SQL Server. • Maintenances – Developing and maintaining stored procedures often demands a specialized skill set not universally possessed by all application developers, potentially causing issues in both application development and maintenance.
  • 13. Simple stored procedure DELIMITER // CREATE PROCEDURE GetEmployeeCount() BEGIN SELECT COUNT(*) AS employee_count FROM employees; END// DELIMITER ; This stored procedure simply returns the count of employees from the employees table.
  • 14. Stored Procedure with Parameters DELIMITER // CREATE PROCEDURE GetEmployeeByDepartment(IN dept_id INT) BEGIN SELECT * FROM employees WHERE department_id = dept_id; END// DELIMITER ; This stored procedure takes a department ID as input parameter and returns all employees belonging to that department.
  • 15. Stored Procedure with Output Parameters DELIMITER // CREATE PROCEDURE GetDepartmentCount(OUT dept_count INT) BEGIN SELECT COUNT(*) INTO dept_count FROM departments; END// DELIMITER ; This stored procedure calculates the count of departments and returns it via an output parameter.
  • 16. Stored Procedure with Conditional Logic: DELIMITER // CREATE PROCEDURE GetHighSalaryEmployees() BEGIN DECLARE min_salary DECIMAL(10, 2); SET min_salary = 50000; SELECT * FROM employees WHERE salary >= min_salary; END// DELIMITER ; This stored procedure retrieves employees with salaries equal to or higher than a specified threshold.
  • 17. To call these stored procedures, you can use the CALL statement followed by the procedure name and any necessary parameters. For example: CALL GetEmployeeCount();
  • 18. How to execute stored procedure 1. Open MySQL Workbench 2. Create New tab to run SQL statements. 3. Enter the SQL statements for stored procedure in your new tab.
  • 19. 4. Execute the store procedure statements by clicking the ‘lightning’ icon shown below. That will call stored procedure in MySQL Workbench. 5. Expand the stored procedure node in right pane. You should see the name of your stored procedure (get_products). If you don’t see it, then hit refresh button next to SCHEMAS
  • 20. Drop a Stored Procedure You can use the MySQL workbench wizard to drop the procedure. To drop any procedure, expand sakila schema Expand Stored Procedures Right-click on sp_GetMovies Click on Drop Stored Procedure.
  • 21. To drop the stored procedure, you can use the drop procedure command. The syntax is following Drop procedure [IF EXISTS] <Procedure Name> In the syntax, the name of the stored procedure must be followed by the Drop Procedure keyword. If you want to drop the sp_getCustomers procedure from the sakila database, you can run the following query. Drop procedure sp_getCustomers When you try to drop the procedure that does not exist on a database, the query shows an error: ERROR 1305 (42000): PROCEDURE sakila.getCustomer does not exist To avoid this, you can include the [IF EXISTS] option in the drop procedure command. When you include the IF EXISTS keyword, instead of an error, the query returns a warning:
  • 24. Summary • A stored procedure is a wrapper of a set of SQL statements stored in the MySQL database server. • The advantages of stored procedures include reduced network traffic, enhanced code reusability, improved security through controlled access, streamlined implementation of business logic, and the ability to grant specific privileges to applications without exposing underlying database structures. • The disadvantages of stored procedures include increased memory usage for each connection, challenges in debugging due to a lack of dedicated tools, and the necessity for a specialized skill set, which not all application developers may possess, leading to potential difficulties in both development and maintenance processes.