为SQLEXCEPTION添加SQL退出处理程序会导致语法错误和意外的文本

时间:2018-11-27 08:57:28

标签: sql stored-procedures syntax-error teradata

我想在过程中添加几个处理程序,简化后的当前版本如下:

REPLACE PROCEDURE DM.AZ_SP ( IN IN_S_DATE DATE, IN IN_E_DATE DATE, OUT sqlMsg_result VARCHAR(133) )
SQL SECURITY INVOKER
BEGIN

    DECLARE V_S_DATE DATE;
    DECLARE V_E_DATE DATE;
    DECLARE V_REPORT_DATE DATE;
    DECLARE sted_id INTEGER DEFAULT 0;

    SET V_S_DATE = IN_S_DATE;
    SET V_E_DATE = IN_E_DATE;
    SET sted_id = 0;



    SET sted_id = 1;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
            BEGIN
                insert into DM.t_sp_logs values (
                    current_timestamp
                ,   'AZ_SP'
                ,   sted_id
                ,   'ERROR code: '  || :SQL_CODE
                );   -- Missing/Invalid SQL statement'E(3707):Syntax error, expected something like an 'END' keyword between ';' and the 'DECLARE' keyword.'.
            END; 
END; -- Unexpected text 'END'.

这是怎么了?如何解决?

1 个答案:

答案 0 :(得分:1)

有一个声明顺序:

DECLARE variables/condition handlers
DECLARE cursors
DECLARE handlers

第一个SET结束了声明部分。

您需要将SET 移到处理程序之后。

REPLACE PROCEDURE DM.AZ_SP ( IN IN_S_DATE DATE, IN IN_E_DATE DATE, OUT sqlMsg_result VARCHAR(133) )
SQL SECURITY INVOKER
BEGIN

    DECLARE V_S_DATE DATE;
    DECLARE V_E_DATE DATE;
    DECLARE V_REPORT_DATE DATE;
    DECLARE sted_id INTEGER DEFAULT 0;

    DECLARE EXIT HANDLER FOR SQLEXCEPTION
            BEGIN
                insert into DM.t_sp_logs values (
                    current_timestamp
                ,   'AZ_SP'
                ,   sted_id
                ,   'ERROR code: '  || :SQL_CODE
                );   -- Missing/Invalid SQL statement'E(3707):Syntax error, expected something like an 'END' keyword between ';' and the 'DECLARE' keyword.'.
            END; 

    SET V_S_DATE = IN_S_DATE;
    SET V_E_DATE = IN_E_DATE;
    SET sted_id = 0;



    SET sted_id = 1;

END; 

或者您使用嵌套的BEGIN / END,每个BEGIN之后都有一个新的声明部分

REPLACE PROCEDURE DM.AZ_SP ( IN IN_S_DATE DATE, IN IN_E_DATE DATE, OUT sqlMsg_result VARCHAR(133) )
SQL SECURITY INVOKER
BEGIN

    DECLARE V_S_DATE DATE;
    DECLARE V_E_DATE DATE;
    DECLARE V_REPORT_DATE DATE;
    DECLARE sted_id INTEGER DEFAULT 0;

    SET V_S_DATE = IN_S_DATE;
    SET V_E_DATE = IN_E_DATE;
    SET sted_id = 0;



    SET sted_id = 1;
    BEGIN
        DECLARE EXIT HANDLER FOR SQLEXCEPTION
            BEGIN
                insert into DM.t_sp_logs values (
                    current_timestamp
                ,   'AZ_SP'
                ,   sted_id
                ,   'ERROR code: '  || :SQL_CODE
                );   -- Missing/Invalid SQL statement'E(3707):Syntax error, expected something like an 'END' keyword between ';' and the 'DECLARE' keyword.'.
            END;
        ..... 
    END;
END;