2

我想检查Oracle中的特定表是否存在,哪种方式更通用和合适,下面列出了2种方式,如果表存在则方式1运行速度快,因为它只运行一个sql

  1. 处理异常并了解它。

    create or replace procedure get_id_only (id out number) as
    begin
    execute immediate 'SELECT id FROM TABLE_NAME where rownum = 1' into id;
    exception    
        when others then
          if (sqlcode = -942) then
            SELECT id into id FROM my_another_table;
          else 
            raise;
          end if;
    end;
    
  2. 检查用户表以查看它是否存在。

    create or replace procedure get_id_only (id out number) as
     count number;
    begin
      SELECT count(*) into count FROM user_tables 
           WHERE table_name = 'TABLE_NAME';
      if (count = 0) then
        SELECT id into id FROM my_another_table;
        return;
      end if;
    
      execute immediate 'SELECT id FROM TABLE_NAME where rownum = 1' into id;
    
    end;
    
4

1 回答 1

1

正如您所说,第一个是最好和最有效的方法。因为捕获“table not found”异常:这避免了检查表是否存在两次的开销;

于 2013-04-09T15:04:34.317 回答