MySQL 错误,"Not allowed to return a result set from a function"?

MySQL error, "Not allowed to return a result set from a function"?

我正在努力研究 mySQL 中的函数,我目前正在制作一个检查列 account_description 的函数,查看描述是否已经存在很有价值。

如果它已经存在,则显示一条消息说明。但是,如果描述不存在,则显示一条不同的消息,说明未找到。

谢谢!

MySQL代码:

DROP FUNCTION IF EXISTS test_glaccounts_description

DELIMITER //

CREATE FUNCTION test_glaccounts_description
(
    check_description VARCHAR(50)
)
RETURNS VARCHAR(50)
BEGIN

DECLARE var_check VARCHAR(50);

SELECT
    account_description INTO var_check
FROM
    general_ledger_accounts
WHERE
    account_description = check_description;

    IF var_check = check_description THEN
        SELECT 'That description already exists.';
    ELSEIF var_check != check_description THEN
        SELECT 'That description does not exist.';
    END IF;

RETURN var_check;

END //

DELIMITER ;

SELECT
    test_glaccounts_description(account_description) as 'Check'
FROM 
    general_ledger_accounts
WHERE
    account_description = 'Accounting';

您不能使用 SELECT 在存储函数中显示消息,您只能通过 RETURN 语句返回单个值。您会在 documentation

中找到它

Statements that return a result set can be used within a stored procedure but not within a stored function. This prohibition includes SELECT statements that do not have an INTO var_list clause and other statements such as SHOW, EXPLAIN, and CHECK TABLE. For statements that can be determined at function definition time to return a result set, a Not allowed to return a result set from a function error occurs (ER_SP_NO_RETSET). For statements that can be determined only at runtime to return a result set, a PROCEDURE %s can't return a result set in the given context error occurs (ER_SP_BADSELECT).