通过执行变量中的语句从存储过程中获取SQLCODE和SQLSTATE

时间:2018-11-15 12:16:41

标签: sql stored-procedures error-handling db2 execute

我有这个:

CREATE OR replace PROCEDURE log_test
                                 ( IN QUERY VARCHAR(24576),
                                   IN LOGTBL varchar(20) ) LANGUAGE SQL
BEGIN
DECLARE v_select_query VARCHAR(24576);
DECLARE v_query VARCHAR(24576);
DECLARE v_logtbl varchar(20);
DECLARE v_errormsg varchar(2048);
DECLARE v_time TIMESTAMP;
DECLARE v_temp_select varchar(1024);
DECLARE stmt STATEMENT;
DECLARE SQLCODE INTEGER DEFAULT 0;
DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
DECLARE CONTINUE HANDLER 
FOR SQLEXCEPTION,SQLWARNING,NOT FOUND
    SET v_sqlcode = SQLCODE;




set v_select_query  = 'Set (?) = ('||QUERY||')';
set v_query  = 'Set (?) = ('||QUERY||')';
set v_bezug  = bezug;
set v_logtbl = logtbl;
set v_time   = CURRENT TIMESTAMP;



PREPARE stmt from v_select_query;

EXECUTE stmt into v_temp_select;

END @

语句查询为

 select count(*) from testtbl;

并且没有sqlstate捕获它就可以工作。

结果是当语句成功或失败时,我希望将sqlcode保存在变量中。但是,现在我只收到一条错误消息,该错误消息是在“”之后出现意外令牌“”。

关于如何解决此问题的任何想法?稍后,我想将带有插入内容的sqlcode记录到另一个表中。

DB2 Windows v10.5

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

根据注释,修复代码中的语法错误。下面的示例将针对Db2-LUW进行编译,但是您的代码中还有其他错误和问题,稍后您将在测试中找到它们。

CREATE OR replace PROCEDURE log_test
( IN QUERY VARCHAR(24576),
  IN LOGTBL varchar(20) ) 
LANGUAGE SQL
specific log_test
BEGIN
    DECLARE SQLCODE INTEGER DEFAULT 0;
    DECLARE SQLSTATE CHAR(5) DEFAULT '00000';
    DECLARE v_select_query VARCHAR(24576);
    DECLARE v_query VARCHAR(24576);
    DECLARE v_logtbl varchar(20);
    DECLARE v_errormsg varchar(2048);
    DECLARE v_time TIMESTAMP;
    DECLARE v_temp_select varchar(1024);
    DECLARE v_sqlcode INTEGER;
    DECLARE v_sqlstate CHAR(5);
    DECLARE v_bezug varchar(1024);

    DECLARE stmt STATEMENT;
    DECLARE CONTINUE HANDLER FOR SQLWARNING,NOT FOUND
        SET v_sqlcode = SQLCODE;
    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
        SET v_sqlstate = SQLSTATE;


    set v_select_query  = 'Set (?) = ('||QUERY||')';
    set v_query  = 'Set (?) = ('||QUERY||')';
    set v_bezug  = 'bezug';
    set v_logtbl = logtbl;
    set v_time   = CURRENT TIMESTAMP;



    PREPARE stmt from v_select_query;

    EXECUTE stmt into v_temp_select;

END@