【问题标题】:Alter Table if column doesn't exist如果列不存在则更改表
【发布时间】:2012-06-16 01:45:03
【问题描述】:

在表中,我想检查特定列是否存在。如果该列不存在,我想更改表并创建该列。

我正在使用 Oracle 11g。

【问题讨论】:

标签: oracle oracle11g alter-table


【解决方案1】:

或者,您可以忽略错误:

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

【讨论】:

    【解决方案2】:

    如果您只想添加不存在的列,只需发出ALTER TABLE ADD (mycolumn ...);。如果语句引发异常 (ORA-01430: column being added already exists in table),则该列已经存在,您可以忽略该异常。

    【讨论】:

      【解决方案3】:

      试试这个:

      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

      【讨论】:

      • pl/sql 语法不正确。你不能在没有 BEGIN 的情况下使用 DECLARE
      【解决方案4】:

      查看 user_tab_columns 表以检查该列是否存在,并进行相应操作

      【讨论】:

        猜你喜欢
        • 2014-08-25
        • 2013-05-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-25
        • 2012-04-15
        • 1970-01-01
        • 2014-01-20
        相关资源
        最近更新 更多