2012-06-13 28 views
3

在表格中,我想檢查一個特定列是否存在。如果該列不存在,我想更改表格並創建該列。如果列不存在,則改變表格

我正在使用Oracle 11g。

+0

可能重複[?如何檢查是否列在PL/SQL將它添加到現有的表之前存在(http://stackoverflow.com/questions/6351823 /如何檢查是否存在先於將其添加到現有表中的pl-sql) –

回答

6

做試試這個:

declare p_count NUMBER; 

select count(1) int p_count 
from ALL_TAB_COLUMNS 
where OWNER = '<SCHEMA_NAME>' 
and TABLE_NAME = '<TABLE_NAME>' 
and COLUMN_NAME = '<COLUMN_NAME>'; 

IF p_count = 0 THEN 
    --add your column 
END IF; 

最終(根據權限)可以使用user_tab_columns

+1

pl/sql語法不正確。 如果沒有BEGIN,則不能使用DECLARE –

1

直視USER_TAB_COLUMNS表來檢查列上存在,並相應地

2

如果您只是想添加一列,如果它不存在,只需發出一個ALTER TABLE ADD (mycolumn ...);。如果語句引發異常(ORA-01430: column being added already exists in table),則列已經存在,您可以忽略該異常。

2

或者,您也可以忽略錯誤:

declare 
    column_exists exception; 
    pragma exception_init (column_exists , -01430); 
begin 
    execute immediate 'ALTER TABLE db.tablename ADD columnname NVARCHAR2(30)'; 
    exception when column_exists then null; 
end; 
/
相關問題