【问题标题】:If I drop a table and the table doesn't exist, I get an error如果我删除一个表并且该表不存在,我会收到一个错误
【发布时间】:2011-01-04 09:26:03
【问题描述】:

我需要删除一张桌子并制作一张新桌子。如果我删除表并且表不存在,我会收到错误

如何检查表是否存在?

我正在开发 Oracle 11g

提前致谢。

【问题讨论】:

  • 发生错误并不是世界末日——如果表不存在,您可以使用异常处理程序处理错误。
  • Oracle: If Table Exists 的可能重复项

标签: oracle oracle11g


【解决方案1】:

类似

select count(*) from user_tables 
where table_name= :table name

select count(*) from dba_tables
where owner = :table owner
and table_name = :table name

或者一个强硬的替代方案:

begin execute immediate 'drop table table_name'; 
exception when others then null; 
end;

【讨论】:

    【解决方案2】:

    你可以这样做:

    DECLARE v_exist PLS_INTEGER;
    BEGIN
    
    SELECT COUNT(*) INTO v_exist
    FROM user_tables
    WHERE table_name = 'YOURTABLEHERE';
    
    IF v_exist = 1 THEN
        EXECUTE IMMEDIATE 'DROP TABLE YOURTABLEHERE';
    END IF;
    

    【讨论】:

      【解决方案3】:

      我一直在使用以下程序来处理这个问题:

      create or replace procedure drop_table_if_exists ( p_table_name varchar2 )
      is
        it_exist number;
      begin
        select count(*) 
           into it_exists
           from user_tables
           where table_name = p_table_name
        ;
        if it_exists >= 1 then
          execute immediate 'drop table '||p_table_name;
        end if;
      end;
      /
      
      exec drop_table_if_exists ( 'TABLE_TO_DROP' );
      

      【讨论】:

        【解决方案4】:
        DECLARE
          eTABLE_OR_VIEW_DOES_NOT_EXIST  EXCEPTION;
          PRAGMA EXCEPTION_INIT(eTABLE_OR_VIEW_DOES_NOT_EXIST, -942);
        BEGIN
          EXECUTE IMMEDIATE 'DROP TABLE SCHEMA.WHATEVER';
        EXCEPTION
          WHEN eTABLE_OR_VIEW_DOES_NOT_EXIST THEN
            NULL;
        END;
        

        分享和享受。

        【讨论】:

          猜你喜欢
          • 2020-11-17
          • 2021-06-15
          • 2014-08-13
          • 2020-01-22
          • 1970-01-01
          • 2015-01-14
          • 1970-01-01
          • 2019-05-05
          • 1970-01-01
          相关资源
          最近更新 更多