2010-01-12 51 views
0

我需要刪除一個表並創建一個新表。如果我刪除表並且該表不存在,則出現錯誤如果我刪除一個表並且該表不存在,我得到一個錯誤

如何檢查表是否存在?

我正在使用Oracle 11g

在此先感謝。

+1

existing = exists – Hogan 2010-01-12 21:52:58

+1

獲取錯誤不是世界的盡頭 - 如果表不存在,您可以使用異常處理程序處理錯誤。 – 2010-01-13 06:30:50

+0

[Oracle:If Table Exists]的可能重複(http://stackoverflow.com/questions/1799128/oracle-if-table-exists) – 2012-06-27 04:44:10

回答

6

你可以做這樣的事情:

DECLARE v_exist PLS_INTEGER; 
BEGIN 

SELECT COUNT(*) INTO v_exist 
FROM user_tables 
WHERE table_name = 'YOURTABLEHERE'; 

IF v_exist = 1 THEN 
    EXECUTE IMMEDIATE 'DROP TABLE YOURTABLEHERE'; 
END IF; 
1

select count(*) from user_tables 
where table_name= :table name 

select count(*) from dba_tables 
where owner = :table owner 
and table_name = :table name 

或嚴厲的選擇:

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

我一直在使用以下步驟來照顧這:

create or replace procedure drop_table_if_exists (p_table_name varchar2) 
is 
    it_exist number; 
begin 
    select count(*) 
    into it_exists 
    from user_tables 
    where table_name = p_table_name 
    ; 
    if it_exists >= 1 then 
    execute immediate 'drop table '||p_table_name; 
    end if; 
end; 
/

exec drop_table_if_exists ('TABLE_TO_DROP'); 
4
DECLARE 
    eTABLE_OR_VIEW_DOES_NOT_EXIST EXCEPTION; 
    PRAGMA EXCEPTION_INIT(eTABLE_OR_VIEW_DOES_NOT_EXIST, -942); 
BEGIN 
    EXECUTE IMMEDIATE 'DROP TABLE SCHEMA.WHATEVER'; 
EXCEPTION 
    WHEN eTABLE_OR_VIEW_DOES_NOT_EXIST THEN 
    NULL; 
END; 

分享和享受。

相關問題