SQL DB2 Drop table if exists 等效

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8270937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 13:24:22  来源:igfitidea点击:

DB2 Drop table if exists equivalent

sqldb2sql-drop

提问by Roman Iuvshin

I need to drop a DB2 table if it exists, or drop and ignore errors.

如果 DB2 表存在,我需要删除它,或者删除并忽略错误。

采纳答案by user918176

First query if the table exists, like

首先查询表是否存在,比如

select tabname from syscat.tables where tabschema='myschema' and tabname='mytable'

and if it returns something issue your

如果它返回一些问题,你的

drop table myschema.mytable

Other possibility is to just issue the drop command and catch the Exception that will be raised if the table does not exist. Just put that code inside try {...} catch (Exception e) { // Ignore } block for that approach.

另一种可能性是仅发出 drop 命令并捕获如果表不存在将引发的异常。只需将该代码放入 try {...} catch (Exception e) { // Ignore } 块中即可。

回答by deltascience

Try this one:

试试这个:

IF EXISTS (SELECT name FROM sysibm.systables WHERE name = 'tab_name') THEN
DROP TABLE tab_name;END IF;

回答by Esperento57

search on systable : if you are on as400 (power i, system i) the system table name is QSYS2.SYSTABLES else try sysibm.systables or syscat.tables (This depends on the operating system)

在 systable 上搜索:如果您在 as400(power i,system i)上,系统表名称是 QSYS2.SYSTABLES 否则尝试 sysibm.systables 或 syscat.tables(这取决于操作系统)

BEGIN    
IF EXISTS (SELECT NAME FROM QSYS2.SYSTABLES WHERE TABLE_SCHEMA = 'YOURLIBINUPPER' AND TABLE_NAME = 'YOUTABLENAMEINUPPER') THEN           
  DROP TABLE YOURLIBINUPPER.YOUTABLENAMEINUPPER;                             
END IF;                                                        
END  ; 

回答by ?sh

The below worked for me in DB2 which queries the SYSCAT.TABLESview to check if the table exists. If yes, it prepares and executes the DROP TABLEstatement.

以下在 DB2 中对我有用,它查询SYSCAT.TABLES视图以检查表是否存在。如果是,它准备并执行DROP TABLE语句。

BEGIN    
   IF EXISTS (SELECT TABNAME FROM SYSCAT.TABLES WHERE TABSCHEMA = 'SCHEMA_NAME' AND TABNAME = 'TABLE_NAME') THEN 
      PREPARE stmt FROM 'DROP TABLE SCHEMA_NAME.TABLE_NAME';
      EXECUTE stmt;
   END IF;                                                        
END