在 db2 中创建存储过程时出错

Error in creating stored procedure in db2

我在 DB2 中创建一个存储过程,它首先检查 table 是否存在,如果存在,它首先删除它,然后尝试创建它。这是代码的样子

CREATE OR REPLACE PROCEDURE Schema.R ()
DYNAMIC RESULT SETS 1
P1: BEGIN
DECLARE SQLCODE integer;
DECLARE table_exists integer default 0;


SELECT 1 INTO table_exists FROM syscat.tables WHERE tabschema = 'schema' AND tabname = 'table1';

IF table_exists = 1
THEN 
    DROP TABLE schema.table1 ;  


    CREATE TABLE schema.table1 AS (
    SELECT
         A.*,
         ...
     ) WITH DATA;
END IF;

END P1

但是一旦部署它,它就会失败并抛出以下错误消息

Create stored procedure returns SQLCODE: -601, SQLSTATE: 42710.
Schema.R: 18: The name of the object to be created is identical to the existing name "schema.table1" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=3.72.30
The name of the object to be created is identical to the existing name "schema.table1" of type "TABLE".. SQLCODE=-601, SQLSTATE=42710, DRIVER=3.72.30
Schema.R - Deploy failed.

发生这种情况是因为编译器发现 table 在编译时 已经存在 。通过为创建使用动态 SQL 来避免它,例如

execute immediate('create table schema.table1 as ( select ...) with data');