MySQL Stored Routines with OUT Parameters

By Tom Nonmacher

In the world of SQL development, stored procedures are a fundamental tool that every developer should have a good understanding of. They are used to encapsulate a sequence of operations into a single executable unit. Not only do they enhance the performance of databases by reducing network traffic, but they also improve the security of a database system. In this blog post, we will dive into MySQL stored procedures and specifically focus on the use of OUT parameters. This will be demonstrated using MySQL 5.7, although these principles can be applied across SQL Server 2016, SQL Server 2017, DB2 11.1 and Azure SQL.

OUT parameters in a stored procedure are used for returning a value to the caller. They are defined in the procedure signature and are assigned within the body of the procedure. When the procedure completes, the caller can check the value of the OUT parameter. To define an OUT parameter, we use the keyword OUT before the parameter name.

Let's take an example. Suppose we have a database of employees, and we want to create a stored procedure that retrieves an employee's full name when provided with their ID. Here's how we would do it in MySQL:

DELIMITER $$
CREATE PROCEDURE GetEmployeeName(OUT empName VARCHAR(100), IN empID INT)
BEGIN
SELECT CONCAT(firstName, ' ', lastName) INTO empName FROM Employees WHERE EmployeeID = empID;
END $$
DELIMITER ;

In the example above, empName is an OUT parameter, and empID is an IN parameter. The stored procedure concatenates the first and last names of the employee with the specified ID and assigns the result to the OUT parameter empName.

To call this stored procedure and get the full name of an employee, you would use the CALL statement as follows:

CALL GetEmployeeName(@empName, 1);
SELECT @empName;

Here, @empName is a user-defined variable that will hold the value of the OUT parameter after the stored procedure is executed. The SELECT statement retrieves the value of @empName.

In conclusion, the OUT parameters in MySQL stored procedures offer a powerful way to return data from a stored procedure back to the caller. They allow for more complex, flexible, and efficient database operations. Although our examples were in MySQL 5.7, the same principles can be applied in SQL Server 2016, SQL Server 2017, DB2 11.1 and Azure SQL with minor variations in syntax. Remember, the knowledge of how to effectively use stored procedures and specifically OUT parameters can be a powerful tool in your SQL developer toolkit.




DD0D62
Please enter the code from the image above in the box below.