2011-06-15 48 views

回答

62

有關Oracle數據庫中列的所有元數據均可使用以下某個視圖訪問。

user_tab_cols; - 用戶擁有的所有表格

all_tab_cols; - 對於用戶可訪問的所有表格

dba_tab_cols; - 用於數據庫中的所有表格。

所以,如果你正在尋找像SCOTT.EMP表ADD_TMS一列,並添加只有當它不存在的列時,PL/SQL代碼將是沿着這些路線的..

DECLARE 
    v_column_exists number := 0; 
BEGIN 
    Select count(*) into v_column_exists 
    from user_tab_cols 
    where column_name = 'ADD_TMS' 
     and table_name = 'EMP'; 
     --and owner = 'SCOTT --*might be required if you are using all/dba views 

    if (v_column_exists = 0) then 
     execute immediate 'alter table emp add (ADD_TMS date)'; 
    end if; 
end; 
/

如果您打算將其作爲腳本運行(不是過程的一部分),最簡單的方法是將alter命令包含在腳本中,並在腳本結尾處查看錯誤(假設您沒有Begin-End for劇本..

如果你有file1.sql

和col2是存在的,當腳本運行時,其他兩列將被添加到表中,日誌會顯示錯誤說「col2」已經存在,所以你應該沒問題。

+1

對於欠缺經驗的Oracle用戶,如果您對列名和表名進行比較,可能會爲您節省一些麻煩:'lower(column_name)= lower('mycol')' – mastaBlasta 2018-01-12 19:32:47

6

通常,我會建議嘗試ANSI-92標準的元表,但我現在看到Oracle不支持它。

-- this works against most any other database 
SELECT 
    * 
FROM 
    INFORMATION_SCHEMA.COLUMNS C 
    INNER JOIN 
     INFORMATION_SCHEMA.TABLES T 
     ON T.TABLE_NAME = C.TABLE_NAME 
WHERE 
    C.COLLATION_NAME = 'columnname' 
    AND T.TABLE_NAME = 'tablename' 

相反,它像looks你需要做的是這樣

-- Oracle specific table/column query 
SELECT 
    * 
FROM 
    ALL_TAB_COLUMNS 
WHERE 
    TABLE_NAME = 'tablename' 
    AND COLUMN_NAME = 'columnname' 

我在那些道歉,我沒有一個Oracle實例,驗證以上。如果它不起作用,請讓我知道,我會刪除這篇文章。

+3

或嘗試和捕獲異常 – Randy 2011-06-15 01:11:20

+7

如果查詢'ALL_TAB_COLUMNS'數據字典視圖,你要包括在'OWNER'謂語列在多個模式中存在相同表的情況下。如果您知道您只對當前用戶模式中的表感興趣,則應該使用「USER_TAB_COLUMNS」視圖。 – 2011-06-15 01:31:34

17

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

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; 
/
+0

很好,很乾淨。謝謝! – 2016-05-24 11:52:33

+0

甜!這可以用於table_exists嗎? – 2017-05-18 20:39:47

+0

不幸的是,沒有「table_exists」。 – grokster 2017-06-19 15:24:24

相關問題