1

我有以下问题。

我想创建一个存储函数,将 entity_id 转换为相应的 sku

这是代码:

CREATE FUNCTION `id2sku`(`entity_id_in` INT)
    RETURNS VARCHAR
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    DECLARE returnvalue varchar(50);

    SELECT `sku` INTO returnvalue FROM catalog_product_entity WHERE entity_id = entity_id_in LIMIT 1;

    return returnvalue;
END

现在我的问题是,如果我触发查询,我会收到以下消息:[Window Title] Error

SQL Error (1064): 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 'LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT' at line 3

我使用的数据库是 MySQL 5.0.51a

提前感谢您的想法。

4

2 回答 2

7

MySQL 默认;用作分隔符,因此当遇到第;9 行的 at 时:

 DECLARE returnvalue varchar(50);

MySQL 认为命令结束 - 它正在尝试执行:

CREATE FUNCTION `id2sku`(`entity_id_in` INT)
    RETURNS VARCHAR(50)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    DECLARE returnvalue varchar(50);

这不是有效的 SQL。

设置新的分隔符:

 DELIMITER $$

 CREATE FUNCTION `id2sku`(`entity_id_in` INT)
    RETURNS VARCHAR(50)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    DECLARE returnvalue varchar(50);

    SELECT `sku` INTO returnvalue FROM catalog_product_entity WHERE entity_id = entity_id_in LIMIT 1;

    return returnvalue;
END
$$

然后,您可以使用以下命令更改分隔符:

DELIMITER ;
于 2011-09-08T10:01:36.287 回答
2

这应该有效:

DELIMITER $$

CREATE FUNCTION `id2sku`(`entity_id_in` INT)
    RETURNS VARCHAR(50)
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN
    DECLARE returnvalue VARCHAR(50);

    SELECT `sku` INTO returnvalue FROM catalog_product_entity WHERE entity_id = entity_id_in LIMIT 1;

    RETURN returnvalue;

    END$$

DELIMITER ;

您没有指定 varchar 长度。:-)

于 2011-09-08T09:33:25.930 回答