如何检查MariaDB语法错误(错误代码1064)?

6pp0gazn  于 2022-11-29  发布在  其他
关注(0)|答案(1)|浏览(266)

我在MariaDB 10上有两个简单的存储过程,用于自动清除表中的数据。第一个从简单的表中读取配置项,并将数据传递给第二个,第二个从物理上删除记录。在测试过程中,一切正常,但现在我得到错误**"错误代码:1064.您的SQL语法中有错误;请查看与您的MariaDB服务器版本对应的手册,了解在第1行0,052 sec "**处使用" NULL "附近的正确语法,我不知道为什么。
程序如下:

CREATE DEFINER=`root`@`10.135.15.%` PROCEDURE `clean_table_checker`()
BEGIN
    DECLARE TMP_TIME_AGO INT(11);
    DECLARE TMP_ID INT(11);
    DECLARE TMP_RETENTION_SECS INT(11);
    DECLARE TMP_DBNAME VARCHAR(45);
    DECLARE TMP_TABLENAME VARCHAR(45);
    DECLARE TMP_TS_FIELD VARCHAR(45);
    DECLARE TMP_LASTUPDATE INT(11);
    DECLARE TMP_RETENTION INT(4);
    DECLARE DONE INT DEFAULT 0;
    DECLARE get_tables CURSOR FOR SELECT `id`, `dbname`, `tablename`, `ts_field`, `lastupdate`, `retention` FROM management.clean_table;    

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
        
    OPEN get_tables;
    
    loop_cursor_ptr: LOOP
        IF DONE THEN
            LEAVE loop_cursor_ptr;
        END IF;

        FETCH get_tables INTO TMP_ID, TMP_DBNAME, TMP_TABLENAME, TMP_TS_FIELD, TMP_LASTUPDATE, TMP_RETENTION;
        SET TMP_TIME_AGO = UNIX_TIMESTAMP(NOW()) - TMP_LASTUPDATE;
        SET TMP_RETENTION_SECS = TMP_RETENTION * 86400;

        IF TMP_LASTUPDATE is NULL THEN
            SET @SQL = CONCAT('UPDATE management.clean_table SET `lastupdate`=',UNIX_TIMESTAMP(NOW()),' WHERE `id`=',TMP_ID,';');
        ELSEIF (TMP_TIME_AGO > TMP_RETENTION_SECS) THEN
            CALL clean_table_proc(TMP_DBNAME, TMP_TABLENAME, TMP_TS_FIELD, TMP_RETENTION_SECS);
            SET @SQL = CONCAT('UPDATE management.clean_table SET `lastupdate`=',UNIX_TIMESTAMP(NOW()),' WHERE `id`=',TMP_ID,';');
        END IF;
        PREPARE STMT FROM @SQL;
        EXECUTE STMT;
        DEALLOCATE PREPARE STMT;

    END LOOP loop_cursor_ptr;

    CLOSE get_tables;
END

有什么想法?建议?

cwtwac6a

cwtwac6a1#

如果您的条件(TMP_LASTUPDATE is NULLTMP_TIME_AGO > TMP_RETENTION_SECS)都不为真,则@SQL的值不会设定,因此会产生NULL。然后,您会尝试从NULL值准备陈述式,这就是您看到错误的原因。您需要新增测试,以判断是否有必要执行查询,例如:

SET @SQL = ''
IF TMP_LASTUPDATE is NULL THEN
    SET @SQL = CONCAT('UPDATE management.clean_table SET `lastupdate`=',UNIX_TIMESTAMP(NOW()),' WHERE `id`=',TMP_ID,';');
ELSEIF (TMP_TIME_AGO > TMP_RETENTION_SECS) THEN
    CALL clean_table_proc(TMP_DBNAME, TMP_TABLENAME, TMP_TS_FIELD, TMP_RETENTION_SECS);
    SET @SQL = CONCAT('UPDATE management.clean_table SET `lastupdate`=',UNIX_TIMESTAMP(NOW()),' WHERE `id`=',TMP_ID,';');
END IF;
IF @SQL != '' THEN
    PREPARE STMT FROM @SQL;
    EXECUTE STMT;
    DEALLOCATE PREPARE STMT;
END IF;

相关问题