1

我想在 Mysql 中创建以下函数,但该函数未创建但失败并出现错误

DELIMITER $$
CREATE FUNCTION MapAccountType(AccountTypeID INT) 
RETURNS VARCHAR(50)
DETERMINISTIC
BEGIN
    DECLARE @AccountType varchar(50);
    SELECT AccountType INTO @AccountType 
            FROM AccountType 
            WHERE AccountTypeID = AccountTypeID);
    RETURN AccountType;
END $$
DELIMITER ;

我的桌子的描述

CREATE TABLE AccountType(
    AccountTypeID INT AUTO_INCREMENT PRIMARY KEY,
    AccountType varchar(100) UNIQUE NOT NULL
);

我得到的错误是

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '@AccountType varchar(50);

我似乎无法找出我做错了什么。有人可以帮忙吗。

4

1 回答 1

0

这应该有效:

DELIMITER $$
CREATE FUNCTION MapAccountType(AccountTypeID INT) 
RETURNS VARCHAR(50)
DETERMINISTIC
BEGIN
    SELECT AccountType INTO @AccountType FROM AccountType
    WHERE AccountTypeID = AccountTypeID;

    RETURN @AccountType;
END $$
DELIMITER ;

这也将起作用:

DELIMITER $$
CREATE FUNCTION MapAccountType(AccountTypeID INT) 
RETURNS VARCHAR(50)
DETERMINISTIC
BEGIN
    DECLARE v_AccountType varchar(50) DEFAULT NULL;

    SELECT AccountType INTO v_AccountType FROM AccountType
    WHERE AccountTypeID = AccountTypeID;

    RETURN v_AccountType;
END $$
DELIMITER ;

第一个示例使用“全局”变量(以“@”符号开头的变量)。第二个示例使用“本地”变量。

于 2012-10-23T22:28:05.567 回答