When creating stored procedures in MySQL, you can specify how parameters behave using three parameter modes: IN, OUT, and INOUT. Each mode determines how data flows between the calling program and the stored procedure.
IN is the default parameter mode if none is specified.
DELIMITER //
CREATE PROCEDURE calculate_bonus(IN employee_id INT, IN bonus_percentage DECIMAL(5,2))
BEGIN
-- Update employee's bonus based on their salary
UPDATE employees
SET bonus = salary * (bonus_percentage / 100)
WHERE id = employee_id;
-- Any modifications to employee_id or bonus_percentage here
-- will not affect the original variables in the calling program
SET employee_id = 0; -- This change is only visible within the procedure
END//
DELIMITER ;
-- Calling the procedure
SET @emp_id = 101;
SET @bonus_pct = 10.5;
CALL calculate_bonus(@emp_id, @bonus_pct);
-- @emp_id still equals 101, it was not changed by the procedure
SELECT @emp_id; -- Will show 101
OUT parameters allow the procedure to return values to the caller.
DELIMITER //
CREATE PROCEDURE get_employee_info(IN emp_id INT, OUT emp_name VARCHAR(100), OUT emp_salary DECIMAL(10,2))
BEGIN
-- Retrieve employee information
SELECT name, salary INTO emp_name, emp_salary
FROM employees
WHERE id = emp_id;
-- If no employee found, variables remain NULL
END//
DELIMITER ;
-- Calling the procedure
SET @id = 101;
SET @name = '';
SET @salary = 0;
CALL get_employee_info(@id, @name, @salary);
-- @name and @salary now contain values set by the procedure
SELECT @name, @salary;