0

我正试图围绕 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';
4

1 回答 1

1

You can't use a SELECT to display the message in a stored function, you are restricted to returning a single value via the RETURN statement. You'll find this covered in the 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).

于 2018-04-25T23:15:43.190 回答