2013-04-09 77 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