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.