哪种方式适合检查表的存在

时间:2013-04-09 14:53:32

标签: sql database performance oracle oracle11g

我想在Oracle中检查一个特定的表存在,哪种方式更通用和适当,我有下面列出的两种方法,如果表存在,方法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;
    

1 个答案:

答案 0 :(得分:1)

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