MySQL存储过程语法困惑

标签 mysql stored-procedures

使用语法形式文档,阅读许多示例和文档,我减少了代码以隔离导致失败的语法,我看不到它......我仍然收到错误。

通过 MySQL 命令行运行

参数:A_scoresmallint,B_scoresmallint

delimiter $$
create procedure my_procedure(A_score smallint, B_score smallint)
begin
    DECLARE  winner BIGINT DEFAULT 0;
    DECLARE  winningScore, losingScore SMALLINT DEFAULT;
    if A_score > B_score then
        SET winningScore = 1;
    elseif A_score < B_score then
        SET winningScore = 2;
    end if;
    start transaction;
        UPDATE
            winners
        SET
            winner = winningScore 
        WHERE
            id = 1
    commit;
end $$
delimiter ;

错误 1064 (42000):您的 SQL 语法有错误;检查手册 对应于您的 MySQL 服务器版本,以便在 '; 附近使用正确的语法。 如果 A_score > B_score 那么 SET 获胜分数 = 1; elseif A_score' 在第 4 行

最佳答案

我发现您忘记编写 SET (在问题的先前版本中)来为变量赋值。

(我将 winingScorelosingScore 的类型更改为字符,因为 smallint 不能是字符串):

-- Be sure to change the default delimiter before writing your procedure
delimiter $$
create procedure my_procedure(A_score smallint, B_score smallint)
begin
    DECLARE  winner BIGINT DEFAULT 0;
    DECLARE  winningScore, losingScore VARCHAR(2) DEFAULT;
    if A_score > B_score then
        SET winningScore = 'A';
    --  ^^^--you forgot this
    elseif A_score < B_score then
        SET winningScore = 'B';
    --  ^^^--and this
    else
        SET winningScore = 'AB';
    --  ^^^--and this
    end if;
    start transaction;
    -- Do whatever your transaction is meant to be
    commit;
end $$
--  ^^--- And I think you're forgetting to put this

-- Be sure to reset the delimiter to ; after you end your procedure
delimiter ;

引用自the reference manual :

Variables can be set directly with the SET statement. See Section 13.7.4, “SET Syntax”.

希望这有帮助

关于MySQL存储过程语法困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32446611/

相关文章:

php - 在 Laravel 中更新模型关系

mysql - Grails 事务永远不会完成

java代码使存储过程在DAO层返回结果集

sql-server - 从 SQL Server 2008 生成 xml

sql - 我正在尝试创建一个存储过程来创建登录名和数据库用户?

mysql - 迁移服务器而不丢失任何数据且不停机的最佳方法(?)

PHP 连接远程 MySQL 服务器失败

php - 在数据库中添加或更新(大)数组值

mysql - MYSQL中如何退出外部IF语句

mysql - 从mysql插入过程获取插入的id