在db2中创建存储过程时出错
我在DB2中创建一个存储过程,它首先检查一个表的存在,如果它存在,它首先删除它,然后尝试创建它。下面是代码的样子在db2中创建存储过程时出错,db2,db2-luw,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 ta
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.
这是因为编译器在编译时看到表已经存在。通过使用动态SQL进行创建来避免这种情况,例如
execute immediate('create table schema.table1 as ( select ...) with data');
这个解决方案是可行的,但为什么会这样呢?在SP中创建表时是否应该始终使用动态SQL?根据回答,编译器会看到“createtable…”,同时也会看到目标表已经存在。在编译过程中,编译器只考虑当前语句,即不考虑上一个DROP表。您可以在编译之前删除表,也可以使用动态SQL(这意味着只有在调用存储过程时,该语句的编译器才会运行)。仔细阅读本页,直到您理解它: