sql - MySQL 语法错误

标签 sql mysql stored-procedures

执行时:

BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        ROLLBACK;
        SELECT 1;
    END;

    DECLARE EXIT HANDLER FOR SQLWARNING
    BEGIN
        ROLLBACK;
        SELECT 1;
    END;

    -- delete all users in the main profile table that are in the MaineU18 by email address
    DELETE FROM ap_form_1 WHERE element_5 IN (SELECT email FROM MaineU18);

    -- delete all users from the MaineU18 table
    DELETE from MaineU18;

    COMMIT;
END;

我得到:

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 'e1:
                DECLARE EXIT HANDLER FOR SQLEXCEPTION
                BEGIN
                        ROLLBACK' at line 2

有什么想法吗?谢谢。

更新 2:

I have tried putting the script into a PROCEDURE:

DELIMITER |
DROP PROCEDURE IF EXISTS temp_clapro|
CREATE PROCEDURE temp_clapro()
BEGIN
    DECLARE EXIT HANDLER FOR SQLEXCEPTION, SQLWARNING ROLLBACK;

    SET AUTOCOMMIT=0;

    -- delete all users in the main profile table that are in the MaineU18 by email address
    DELETE FROM ap_form_1 WHERE element_5 IN (SELECT email FROM MaineU18);

    -- delete all users from the MaineU18 table
    DELETE from MaineU18;

    COMMIT;
    SET AUTOCOMMIT=1;
END
|
DELIMITER ;
CALL temp_clapro();

我仍然遇到问题:

Query OK, 0 rows affected (0.00 sec)

Query OK, 0 rows affected (2.40 sec)

Query OK, 0 rows affected (2.40 sec)

Query OK, 0 rows affected (2.40 sec)

Query OK, 0 rows affected (2.40 sec)

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 'END;
|
DELIMITER ;
CALL temp_clapro()' at line 1

更新3:

看来我的许多问题都来自于我使用“SOURCE”命令从文件运行脚本这一事实。如果我在文件中只有 DROP 和 CREATE 命令,并在文件外部运行 DELIMITER 和 CALL 命令,则一切正常,不会出现错误。

有办法从单个脚本文件运行它吗?

最佳答案

您似乎使用 BEGIN 作为一组临时语句的开头,就像在 SQL Server 中所做的那样。

MySQL 不支持此功能。您只能在存储过程、存储函数或触发器的主体中DECLARE

http://dev.mysql.com/doc/refman/en/declare.html :

DECLARE is allowed only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

http://dev.mysql.com/doc/refman/en/begin-end.html :

BEGIN ... END syntax is used for writing compound statements, which can appear within stored programs.

<小时/>

回复您的评论和更新的问题:我不知道为什么失败。我刚刚自己尝试了一下,效果很好。您使用什么版本的 MySQL?

关于sql - MySQL 语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1526817/

相关文章:

mysql - 选择具有最新日期的行

mysql - 查询和存储过程返回不同的结果

c# - 使 Entity Framework 将存储过程结果集列解释为 bool 而不是 int?

mysql - 复杂选择逻辑的 SQL 字段更新语法问题

sql - SQL 中的多重计数查询返回什么?

php - mysql_fetch_array() : supplied argument is not a valid MySQL result resource (on simple query)

html - 验证密码和用户名nodejs mysql

mysql - 根据条件从2个不同的表中选择数据; mysql

java.sql.SQLException : Column 'JOB_ID' not found

mysql - mysql过程中的语法错误错误代码1064