对于大多数人来说,这可能是一个微不足道的问题......下面是我在 MySQL 中创建的一个存储函数:
DROP PROCEDURE IF EXISTS teamSize;
DELIMITER //
CREATE PROCEDURE teamSize(IN teamName VARCHAR(50), IN teamYear INT(4), OUT noOfPlayers INT)
BEGIN
IF teamName IN (SELECT teamName FROM team) THEN
SELECT COUNT(playerID) INTO noOfPlayers
FROM team
JOIN teamAllocation
ON teamAllocation.teamID = team.teamID
WHERE team.teamName = teamName
AND team.teamYear = teamYear;
ELSE
SELECT "That team does not exist in the database" AS "Error Message";
END IF;
END //
DELIMITER ;
我制作了这个函数,以便我可以计算给定团队在给定年份的规模。团队名称和团队年份被解析为参数值。对于此功能,如果用户输入的团队名称在数据库中不存在,我希望显示用户友好的错误消息。
例如:我输入一个确实存在的团队,我得到以下结果,正如我所料:
mysql> CALL teamSize("U11 Orange", 2012, @noOfPlayers);
--------------
CALL teamSize("U11 Orange", 2012, @noOfPlayers)
--------------
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @noOfPlayers;
--------------
SELECT @noOfPlayers
--------------
+--------------+
| @noOfPlayers |
+--------------+
| 2 |
+--------------+
1 row in set (0.00 sec)
mysql>
...但是如果我输入一个我知道数据库中不存在的团队,我会得到以下信息:
mysql> CALL teamSize("jkgefkrkvbey", 2012, @teamSize);
--------------
CALL teamSize("jkgefkrkvbey", 2012, @teamSize)
--------------
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT @teamSize;
--------------
SELECT @teamSize
--------------
+-----------+
| @teamSize |
+-----------+
| 0 |
+-----------+
1 row in set (0.00 sec)
mysql>
对于解析为函数的团队名称不存在的情况,我想要的是以下内容:
+------------------------------------------+
| Error Message |
+------------------------------------------+
| That team does not exist in the database |
+------------------------------------------+
1 row in set (0.00 sec)
mysql>
如果有人对我如何实现上述目标有一些反馈或建议,将不胜感激。
提前致谢!