在db2

时间:2018-04-17 14:53:09

标签: db2 db2-luw

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

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.

1 个答案:

答案 0 :(得分:1)

这是因为编译器发现该表在编译时已经存在 。通过使用动态SQL来创建例如

来避免它
execute immediate('create table schema.table1 as ( select ...) with data');