2013-04-09 37 views
2

我想检查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; 
    
+0

我推荐方法#2。 – 2013-04-09 14:56:33

+0

你能给出一个理由吗?它每次都会碰到user_tables,所以会产生额外的成本。 – user2166163 2013-04-09 14:58:09

+3

为什么你需要检查一个表的存在?这是存储过程的一个不寻常的要求。这可能表明存在需要首先解决的另一个问题。 – 2013-04-09 15:20:14

回答

1

正如你说的第一个是最好的和最有效的方式。因为捕获“找不到表”异常:这样可以避免检查表是否存在两次;

+1

我不同意 - 使用异常处理程序作为'goto'不被认为是好的做法。 – 2013-04-09 15:30:31

相关问题