🔔 Level Up Your Database & Programming Skills!
Subscribe to our channel for beginner-friendly tutorials on MySQL, Oracle DB, SQL, and Java!
▶ Subscribe to Ram N JavaIntroduction: MySQL Stored Procedures with Parameters
A Stored Procedure in MySQL allows you to group multiple SQL statements into a reusable routine stored directly on the database server. This approach reduces network latency, centralizes business logic, and improves application security.
In this guide, you will learn how to create and execute a procedure called get_city_name using MySQL Workbench. It takes a City ID as an input parameter (IN) and returns the matching City Name via an output parameter (OUT).
Step 1: Defining IN and OUT Parameters
Parameters allow stored routines to receive data and return computed results:
- city_id (IN INT): The input parameter passed by the caller to look up a specific city record.
- city_name (OUT VARCHAR): The output variable that stores and passes back the retrieved city name.
Step 2: Stored Procedure Logic
Inside the procedure body between BEGIN and END, a query reads the city name into our output parameter:
CREATE PROCEDURE `get_city_name` (
IN city_id INT,
OUT city_name VARCHAR(50)
)
BEGIN
SELECT name
INTO city_name
FROM City
WHERE ID = city_id;
END
In MySQL Workbench, click Apply to review the SQL script and finish the routine setup.
Step 3: Calling and Testing the Procedure
To execute this procedure from a SQL query editor, pass a specific ID value and read the output using a user session variable:
-- Set input parameter SET @city_id = 1; -- Call the procedure with input and output variables CALL get_city_name(@city_id, @city_name); -- View the output parameter result SELECT @city_name;
When you execute this block, MySQL looks up the row where ID = 1, maps its name (e.g., Kabul) to @city_name, and displays the result.
very good video and details
ReplyDeletemobile and website application developer