在sqlserver中,有if exit()这样的语句,但是在oracle中却没有。
如果直接使用drop table那么如果表不存在会报错,导致后续语句无法运行。因此可以通过一个存储过来来进行判断。
主要是查询all_tables表的TABLE_NAME和OWNER,如果表存在,则执行execute immediate 'drop table TABLE_NAME';
--判断表是否存在,如果存在则删除
declare
num number;
begin
select count(1) into num from all_tables where TABLE_NAME = 'EMP' and OWNER='SCOTT';
if num=1 then
execute immediate 'drop table EMP';
end if;
end;
第二种是不作预先判断,而是直接默认通过判断,然后使用 exception 来捕获异常
比如我这里不判断表中是否有满足条件的记录,默认它有,如果没有就在异常中进行处理
declare
v_1 number;
begin
select vip_level into v_1 from T_VIP where 1=0;
exception
when no_data_found then
dbms_output.put_line('无记录');
end;
第三种是利用 Oracle 原有的 Exists 语法,如下
declare
v_cnt number;
begin
select count(1)
into v_cnt
from dual
where exists (select * from t_vip where col=1);
if v_cnt = 0 then
dbms_output.put_line('无记录');
end if;
end;
通过在语句的外面套上一层dual,来使用oracle原有的exists语法
虽然和第一种看起来类似,但分析执行计划可以知道,性能比以上两种都要好得多,与MSSQL的 if exists 最接近,推荐使用。