Search code examples
sqlstored-procedureserror-handlingdb2execute

Get SQLCODE and SQLSTATE from stored procedure with executing a statement from variable


I have this:

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 @

The statement query is

 select count(*) from testtbl;

and without the sqlstate catching it works.

The result is that I want the sqlcode saved in the variables when the statement is successful or fails. However now I only get an error message that after "" the unexpected token "".

Any ideas on how to fix this? I later want to log the sqlcode with an insert into another table.

DB2 Windows v10.5

Thanks for your help


Solution

  • As per comments, fix the syntax errors in your code. The example below will compile for Db2-LUW, but there are other errors and problems in your code that you will find later with testing.

    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@