我编写了以下存储过程:
DELIMITER $$
CREATE PROCEDURE `getroom`(OUT `free_room` INT)
BEGIN
SELECT room INTO free_room FROM admins WHERE free = 1 LIMIT 1 FOR UPDATE;
UPDATE admins SET free = 0 WHERE room = free_room;
END$$
DELIMITER ;
我正在尝试查询表中的空闲房间,锁定该行,以便其他用户无法同时查询它,并将其设置为最后不自由。
我的问题是:
1)如何在不执行其他SELECT语句的情况下自动调用存储过程并获取 free_room 值(就像我运行SELECT语句一样)?
2)由于我没有传递任何参数(没有“IN”值),为什么我不能运行CALL getroom()
succssfully?我收到以下错误:
PROCEDURE getroom的参数数量不正确;预期1,得到0
希望我的问题足够清楚!
答案 0 :(得分:1)
您可以改为创建函数:
DELIMITER $$
CREATE FUNCTION `getroom`() RETURNS INT
BEGIN
DECLARE free_room INT;
SELECT room INTO free_room FROM admins WHERE free = 1 LIMIT 1 FOR UPDATE;
UPDATE admins SET free = 0 WHERE room = free_room;
RETURN free_room;
END$$
DELIMITER ;
然后只使用:
SELECT getroom();
答案 1 :(得分:0)
尝试:
DELIMITER $$
CREATE PROCEDURE `getroom`()
BEGIN
SELECT @free_room := room
FROM admins
WHERE free = 1
LIMIT 1
FOR UPDATE;
UPDATE admins
SET free = 0
WHERE room = @free_room;
END$$
DELIMITER ;
答案 2 :(得分:0)
DELIMITER $$
CREATE PROCEDURE `getroom`()
BEGIN
DECLARE free_room INT;
SELECT room INTO free_room FROM admins WHERE free = 1 LIMIT 1 FOR UPDATE;
UPDATE admins SET free = 0 WHERE room = free_room;
SELECT free_room;
END$$
DELIMITER ;