Oracle drop if exists

在Oracle数据库中,删除表、视图等对象时,为避免因对象不存在而引发错误,可以使用自定义的存储过程实现类似于SQL Server的`DROP IF EXISTS`功能。本文介绍了如何创建和使用这个存储过程,确保执行安全且无干扰。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考https://stackoverflow.com/questions/1799128/oracle-if-table-exists

我的官方博客http://blog.alei.tech ,转载请注明。网页地址https://alei.tech/2016/08/12/%E5%9C%A8Oracle%E6%95%B0%E6%8D%AE%E4%B8%AD%E5%AF%BB%E6%89%BE%E4%B8%80%E4%B8%AA%E5%80%BC/

场景

  • 删除表,视图等对象时,静默执行,不返回报错信息
  • 类似dorp table if exists,语句可反复执行
  • 开发人员编写sql,让实施人员执行
  • 直接写drop table abc,如果abc表已经被删除或者不存在,返回报错信息,对于不懂sql的实施人员来说,会产生干扰

代码示例

创建存储过程

  • 适用于drop table, procedure, function, trigger, view, sequence
    create or replace procedure dropObject(ObjName varchar2,ObjType varchar2)
    is
     v_counter number := 0;   
    begin    
      if upper(ObjType) = 'TABLE' then
        select count(*) into v_counter from user_tables where table_name = upper(ObjName);
        if v_counter > 0 then          
          execute immediate 'drop table ' || ObjName || ' cascade constraints';        
        end if;   
      end if;
      if upper(ObjType) = 'PROCEDURE' then
        select count(*) into v_counter from User_Objects where object_type = 'PROCEDURE' and OBJECT_NAME = upper(ObjName);
          if v_counter > 0 then          
            execute immediate 'DROP PROCEDURE ' || ObjName;        
          end if; 
      end if;
      if upper(ObjType) = 'FUNCTION' then
        select count(*) into v_counter from User_Objects where object_type = 'FUNCTION' and OBJECT_NAME = upper(ObjName);
          if v_counter > 0 then          
            execute immediate 'DROP FUNCTION ' || ObjName;        
          end if; 
      end if;
      if upper(ObjType) = 'TRIGGER' then
        select count(*) into v_counter from User_Triggers where TRIGGER_NAME = upper(ObjName);
          if v_counter > 0 then          
            execute immediate 'DROP TRIGGER ' || ObjName;
          end if; 
      end if;
      if upper(ObjType) = 'VIEW' then
        select count(*) into v_counter from User_Views where VIEW_NAME = upper(ObjName);
          if v_counter > 0 then          
            execute immediate 'DROP VIEW ' || ObjName;        
          end if; 
      end if;
      if upper(ObjType) = 'SEQUENCE' then
        select count(*) into v_counter from user_sequences where sequence_name = upper(ObjName);
          if v_counter > 0 then          
            execute immediate 'DROP SEQUENCE ' || ObjName;        
          end if; 
      end if;
    end;
    

使用存储过程

  • 创建temp_table表之前,判断,if exists then drop
  • 此语句示例在pl/sql developer中执行
  • ”/”必须在行首,之前不能有空格
    begin
      dropObject('temp_table','table');
    end;
    /
    create table
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值