Oracle中的多个“立即执行”查询

时间:2011-02-23 13:25:58

标签: oracle9i

我有这样的查询序列:

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

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

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

但是当我尝试在SQL Scratchpad中执行它时,它说“遇到符号开始”,这表明所有查询都必须在一个开始... 如果我删除所有的开始结束exept为第一个开始和最后结束它给了我 “无效的SQL语句”如何使用上层模式执行多个drop table或多个create table并检查表是否存在?我知道我的exception when others then null;样式被认为是不好的做法,类似于其他语言中的空catch(),但这是我检查oracle中是否存在表格的最简单方法

1 个答案:

答案 0 :(得分:1)

BEGIN
  EXECUTE IMMEDIATE 'drop table mytable1';

  EXECUTE IMMEDIATE 'drop table mytable2';

  EXECUTE IMMEDIATE 'drop table mytable3';
EXCEPTION
  WHEN OTHERS THEN
    NULL;
END;

工作正常。


如果你问我,exception when others then null - 应该避免。如果要检查表是否存在 - 请查询USER_TABLES

DECLARE
  V_EXISTS NUMBER;

BEGIN

SELECT 1 INTO V_EXISTS FROM USER_TABLES WHERE TABLE_NAME = 'TEST';

IF V_EXISTS = 1 THEN
  EXECUTE IMMEDIATE 'DROP TABLE TEST';
END IF;

EXCEPTION
  WHEN NO_DATA_FOUND THEN
    DBMS_OUTPUT.PUT_LINE('Table not found');
END;

Regd:您的评论,如果想要在您的问题中使用该方法,请将其包装在外部匿名块中

BEGIN

  BEGIN
    EXECUTE IMMEDIATE 'drop table mytable1';
  EXCEPTION
    WHEN OTHERS THEN
      NULL;
  END;

  BEGIN
    EXECUTE IMMEDIATE 'drop table mytable2';
  EXCEPTION
    WHEN OTHERS THEN
      NULL;
  END;

  BEGIN
    EXECUTE IMMEDIATE 'drop table mytable3';
  EXCEPTION
    WHEN OTHERS THEN
      NULL;
  END;

END;

结果:

SQL> BEGIN
  2  
  3    BEGIN
  4      EXECUTE IMMEDIATE 'drop table mytable1';
  5    EXCEPTION
  6      WHEN OTHERS THEN
  7        NULL;
  8    END;
  9  
 10    BEGIN
 11      EXECUTE IMMEDIATE 'drop table mytable2';
 12    EXCEPTION
 13      WHEN OTHERS THEN
 14        NULL;
 15    END;
 16  
 17    BEGIN
 18      EXECUTE IMMEDIATE 'drop table mytable3';
 19    EXCEPTION
 20      WHEN OTHERS THEN
 21        NULL;
 22    END;
 23  
 24  END;
 25  
 26  /

PL/SQL procedure successfully completed.

SQL>