简体   繁体   中英

DB2 - How do I create a Stored Procedure that ignores errors?

I am trying to create a simple stored procedure in DB2 that performs the following actions:

  1. Drop table "DELETE_ME"
  2. Create table "DELETE_ME"
  3. Insert into table "DELETE_ME"

Basically, if the table DELETE_ME already exists, the stored procedure executes fine. If it does not exist, then the Stored Procedure fails with the following error:

Lookup Error - DB2 Database Error: ERROR [42704] [IBM][DB2/LINUXX8664] SQL0204N  "SARTS02T.DELETE_ME" is an undefined name.

I completely understand this. However, I was hoping to set the procedure up to ignore this error (and all errors) that way the procedure can work as a deployment script as well. On the first deployment, it will ignore the drop table line and jump right to building the table.

I found a CREATE PROCEDURE option called CONTINUE AFTER FAILURE however I am receiving an error. Please see my code and error below. Thanks for your help!!!

CODE:

CREATE OR REPLACE PROCEDURE TEST_PROC LANGUAGE SQL CONTINUE AFTER FAILURE
BEGIN
  DROP TABLE DELETE_ME;

  CREATE TABLE DELETE_ME (
  COLUMN_A DECIMAL(5)
  );

  INSERT INTO DELETE_ME (COLUMN_A) VALUES (69);

  COMMIT;

END;

ERROR:

Lookup Error - DB2 Database Error: ERROR [42601] [IBM][DB2/LINUXX8664] SQL0104N  An unexpected token "CONTINUE AFTER FAILURE" was found following "ST_PROC LANGUAGE SQL".  Expected tokens may include:  "<space>".

The BEGIN ... END section is called a compound statement which allows various declarations and other statements, including other compound statements, to be included inside it.

You'll want to declare a condition handler. You could do it something like this.

CREATE OR REPLACE PROCEDURE TEST_PROC
      LANGUAGE SQL
      COMMIT ON RETURN YES
  BEGIN
    DECLARE CONTINUE HANDLER FOR SQLSTATE '42704'  -- or SQLEXCEPTION
      BEGIN
          -- insert any code here when DROP fails
      END;

    DROP TABLE DELETE_ME;

    CREATE TABLE DELETE_ME 
    (  COLUMN_A DECIMAL(5)
    );

    INSERT INTO DELETE_ME (COLUMN_A)
                   VALUES (69);

  END;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM