How to Create And Call Stored Procedures In MySQL?

8 minutes read

To create and call stored procedures in MySQL, you can follow these steps:

  1. Connect to the MySQL Server: Open the MySQL command-line client or any other MySQL client tool and connect to the MySQL server using appropriate login credentials.
  2. Create a New Stored Procedure: Use the CREATE PROCEDURE statement to create a new stored procedure. The basic syntax is as follows:
1
2
3
4
CREATE PROCEDURE procedure_name ([IN|OUT|INOUT] parameter_name data_type, ...)
    BEGIN
        -- SQL statements
    END;


  • Replace procedure_name with the desired name for your stored procedure.
  • Specify the parameters within the parentheses, using the IN, OUT, or INOUT keywords to define the type of parameter.
  • Use the BEGIN and END keywords to enclose the SQL statements that the procedure should execute.
  1. Write the SQL Statements: Within the BEGIN and END block, write the SQL statements that you want the stored procedure to execute. You can include any valid SQL statements, such as queries, data manipulation statements (INSERT, UPDATE, DELETE), or control flow statements (IF, WHILE, etc.). Ensure that each statement ends with a semicolon (;).
  2. Save the Stored Procedure: Execute the CREATE PROCEDURE statement to save the stored procedure in the MySQL server. If there are no errors, it will be created successfully.
  3. Call the Stored Procedure: To call the stored procedure, use the CALL statement followed by the name of the stored procedure and any required arguments.
1
CALL procedure_name(argument1, argument2, ...);


  • Replace procedure_name with the name of the stored procedure you want to call.
  • Specify the appropriate arguments within the parentheses if the stored procedure expects any.
  1. Execute the CALL Statement: Execute the CALL statement to run the stored procedure. The designated SQL statements within the stored procedure will be executed, and the result, if any, will be returned or displayed.
  2. Drop the Stored Procedure (optional): If you no longer need the stored procedure, you can use the DROP PROCEDURE statement followed by the name of the stored procedure to remove it from the MySQL server.


These steps outline the process of creating and calling stored procedures in MySQL. You can adapt them to fit your specific requirements and utilize the power and flexibility of stored procedures in your database management tasks.

Best Managed MySQL Hosting Providers in 2024?

1
DigitalOcean

Rating is 5 out of 5

DigitalOcean

2
AWS

Rating is 4.9 out of 5

AWS

3
Vultr

Rating is 4.8 out of 5

Vultr

4
Cloudways

Rating is 4.7 out of 5

Cloudways


What are the benefits of using stored procedures in MySQL?

There are several benefits of using stored procedures in MySQL:

  1. Reusability: Stored procedures allow you to define a set of SQL statements that can be reused multiple times within the database. This eliminates the need to write the same SQL code multiple times, improving code maintainability and reducing the chances of errors.
  2. Performance: Stored procedures typically offer better performance compared to executing individual SQL statements. Once compiled and stored in the database, the execution plan can be optimized, resulting in faster query processing and reduced network traffic.
  3. Modularity: With stored procedures, you can break down complex tasks into smaller modules. This improves code organization and makes it easier to understand, test, and maintain database logic.
  4. Security: Stored procedures can enhance security by allowing you to grant precise access controls to users. You can grant specific permissions to execute the stored procedure while restricting direct access to underlying tables or other sensitive data.
  5. Encapsulation: Stored procedures enable you to encapsulate business logic within the database itself. This helps to enforce business rules consistently across different applications or clients accessing the database.
  6. Ease of maintenance: By centralizing database logic in stored procedures, it becomes easier to modify or update the logic without affecting the various applications that make use of the database. This reduces the overall maintenance effort required.
  7. Version control: Using stored procedures allows you to have version control over your database logic. You can keep track of changes and roll back to previous versions if necessary, providing better control and auditability.
  8. Reduced network traffic: By executing complex operations on the server side using stored procedures, you can minimize the amount of data transferred between the database server and application server. This can greatly reduce network traffic, especially in scenarios where large datasets are involved.


Overall, using stored procedures in MySQL enhances code reusability, performance, security, modularity, and maintenance, making them a powerful tool for database development.


How to modify an existing stored procedure in MySQL?

To modify an existing stored procedure in MySQL, you can use the ALTER PROCEDURE statement. Here is the general syntax:

1
2
3
4
5
6
7
ALTER PROCEDURE procedure_name [characteristic ...]

[procedure_parameter_declaration ...]

BEGIN
    -- Modify the procedure logic here
END;


Here's a step-by-step explanation:

  1. Use the ALTER PROCEDURE statement followed by the name of the stored procedure you want to modify.
  2. Add any characteristics (e.g., CONTAINS SQL, NO SQL, etc.) that describe the behavior of the procedure.
  3. If the stored procedure has any parameters, redeclare them using procedure_parameter_declaration.
  4. Use the BEGIN and END keywords to enclose the modified procedure logic.
  5. Update the procedure logic inside the BEGIN and END block as per your requirements.


Example: Let's assume we have an existing stored procedure named get_customer_count, which returns the count of customers. We want to modify it to include additional filtering criteria.

1
2
3
4
5
6
7
8
DELIMITER //

ALTER PROCEDURE get_customer_count()
BEGIN
    SELECT COUNT(*) FROM customers WHERE country = 'USA';
END//

DELIMITER ;


In this example, we modified the get_customer_count procedure to only count customers from the USA.


Always remember to use the DELIMITER command to change the delimiter temporarily to something other than ; when executing procedures, triggers, or functions that contain semicolons, as seen in the example.


How to call a stored procedure from another stored procedure in MySQL?

To call a stored procedure from another stored procedure in MySQL, you can use the CALL statement followed by the name of the stored procedure along with the appropriate parameters.


Here's an example:

  1. Create the first stored procedure, let's call it proc1, which accepts some parameters:
1
2
3
4
5
6
7
DELIMITER $$
CREATE PROCEDURE proc1(parameter1 INT, parameter2 VARCHAR(255))
BEGIN
    -- Body of the stored procedure
    -- Do some operations
END$$
DELIMITER ;


  1. Create the second stored procedure, proc2, which calls the proc1 stored procedure:
1
2
3
4
5
6
7
8
DELIMITER $$
CREATE PROCEDURE proc2()
BEGIN
    -- Body of the stored procedure
    -- Call proc1 with parameters
    CALL proc1(123, 'example');
END$$
DELIMITER ;


In this example, the proc2 stored procedure calls the proc1 stored procedure with parameters 123 and 'example' using the CALL statement.


You can then execute the proc2 stored procedure using the CALL statement:

1
CALL proc2();


This will execute the proc2 stored procedure, which will in turn call the proc1 stored procedure.


What is the use of DECLARE statement in a stored procedure in MySQL?

The DECLARE statement in a stored procedure in MySQL is used to define and declare local variables within the scope of the stored procedure. These variables can be used to store intermediate results or hold values that need to be used within the procedure.


The DECLARE statement allows developers to specify the name, data type, and default value (if any) for each variable. These variables can then be referenced and manipulated within the stored procedure, making it easier to perform complex calculations or to store temporary data.


By using local variables declared with the DECLARE statement, developers can improve code readability, modularity, and code reusability. It also provides a way to share information between different parts of the stored procedure without the need for temporary tables or other forms of data storage.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To get stored data by delimiter (;) in MySQL, you can use the SUBSTRING_INDEX function along with the LOCATE function. To extract values between delimiters, you would first check for the position of the delimiter using the LOCATE function, then use the SUBSTRI...
To connect to a MySQL database, you need to follow these steps:Install MySQL: Begin by installing MySQL on your computer or server. You can download the MySQL Community Server from the official website and follow the installation instructions for your operatin...
Sessions in PHP are reasonably secure but require proper implementation and additional measures to ensure maximum security. PHP uses a unique session ID for each user, which is stored as a cookie on the user's browser. This session ID is used to identify t...