3

对于大多数人来说,这可能是一个微不足道的问题......下面是我在 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>

如果有人对我如何实现上述目标有一些反馈或建议,将不胜感激。

提前致谢!

4

1 回答 1

2

我认为您的问题是术语的重载teamName。由于teamName是您的过程的参数,因此以下查询:

SELECT teamName FROM team

相当于:

SELECT 'foo' FROM team

'foo'对于中的每条记录,它总是会返回一次字符串team(因此IF 'foo' IN ...条件始终为真)。建议您重命名参数,以免与列名冲突。

此外,您不需要IF以您现在的方式执行。相反,为什么不:

IF (SELECT COUNT(*) FROM team WHERE teamName = new_parameter_name) THEN ...

顺便说一句,我更喜欢引发 SQL 错误(例如,通过调用不存在的过程)而不是返回消息字符串。

于 2012-05-08T00:44:27.533 回答