删除DB2表(如果存在) [英] Drop DB2 table if exists
问题描述
在我的脚本中,我必须对联接表进行大量选择,因此我决定将这种联接放入临时表中。
In my script I have to do a lot of selects to a joined table, so instead I decided to put this join into a temporal table.
首先我想:
1. Create table
2. Put the data from the join into a table
3. Drop the table
但是后来我想到,如果脚本在删除表之前失败了怎么办?
But then I thought, what if the script fails before I dropped the table?
所以我决定去:
1. Drop the table
2. Create the table
3. Put the data from the join into a table
我不介意在下次运行脚本之前是否将表保留在那里,因此第二个选项也适用。
I don't really mind if the table is left there until the next time I run the script, so the second option works too.
但是如果有人已经放下桌子怎么办?
But what if somebody had already dropped the table?
我看到某些系统存在 drop if if,但不幸的是没有DB2。我想要做的事情不会使脚本在放置表失败时消失。
I saw some systems have a "drop if exists" but unfortunately not DB2. I would like to do something that won't make the script die when the drop table fails.
想法?在任何一个?谢谢!
Ideas? On any of this? Thanks!
编辑:我忘了说这是在PERL脚本中!
I forgot to say this is in a PERL script!
推荐答案
最好的方法是使用匿名块,例如代码
The best way to do this is by using an annonymous block like in this code
您需要在动态sql中调用放置表,并在块中捕获异常。
You need to call the drop table in a dynamic sql, and catch the exception in the block.
--#SET TERMINATOR @
begin
declare statement varchar(128);
declare continue handle for sqlstate '42710' BEGIN END;
SET STATEMENT = 'DROP TABLE MYTABLE';
EXECUTE IMMEDIATE STATEMENT;
end @
此代码将在DB2中正常运行。它不必是过程或函数的一部分。
This code will run normally in DB2. It does not need to be part of a procedure nor function.
这篇关于删除DB2表(如果存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!