## 存储过程 - 参数
参数使存储过程更灵活和有用。在MySQL中,参数有三种模式:
- IN – 调用程序必须将参数传递给存储过程,参数的值受到保护。
- OUT – 参数值可以在存储过程中更改,并将其新值传递回给调用程序。存储过程在启动时无法访问参数的初始值。
- INOUT – IN和OUT参数的组合。调用程序可以传递参数,存储过程可以修改参数,并将新值传递回给调用程序。
获取北京总公司的所有雇员:
```
DELIMITER $$
DROP PROCEDURE IF EXISTS get_bj_employees$$
CREATE PROCEDURE get_bj_employees()
BEGIN
SELECT * FROM employee WHERE office_id = 1000;
END$$
DELIMITER ;
```
调用存储过程:
call get_bj_employees();
获取某地的所有雇员:
```
DELIMITER $$
DROP PROCEDURE IF EXISTS get_office_employees$$
CREATE PROCEDURE get_office_employees(IN p_office_id int)
BEGIN
SELECT * FROM employee WHERE office_id = p_office_id;
END$$
DELIMITER ;
```
调用存储过程:
call get_office_employees(1000);
获取某地的雇员总数:
```
DELIMITER $$
DROP PROCEDURE IF EXISTS count_office_employees$$
CREATE PROCEDURE count_office_employees(
IN p_office_id int,
OUT p_total int
)
BEGIN
SELECT count(*) INTO p_total FROM employee WHERE office_id = p_office_id;
END$$
DELIMITER ;
```
调用存储过程:
call count_office_employees(1000, @p_total);
select @p_total;
步进计数器:
```
DELIMITER $$
DROP PROCEDURE IF EXISTS set_counter$$
CREATE PROCEDURE set_counter(INOUT count int, IN step int)
BEGIN
SET count = count + step;
END$$
DELIMITER ;
```
调用存储过程:
set @counter = 100;
call set_counter(@counter, 100); // 结果为 200
call set_counter(@counter, 100); // 结果为 300
call set_counter(@counter, 50); // 结果为 350
select @counter; // 结果为 350