【问题标题】:Modify a column to NULL - Oracle将列修改为 NULL - Oracle
【发布时间】:2013-03-17 11:20:49
【问题描述】:

我有一个名为CUSTOMER 的表,列数很少。其中之一是Customer_ID

最初Customer_IDWILL NOT 接受NULL 值。

我已经从代码级别进行了一些更改,以便 Customer_ID 列默认接受 NULL 值。

现在我的要求是,我需要再次使此列接受NULL 值。

为此,我添加了执行以下查询:

ALTER TABLE Customer MODIFY Customer_ID nvarchar2(20) NULL

我收到以下错误:

ORA-01451 error, the column already allows null entries so
therefore cannot be modified

这是因为我已经让 Customer_ID 列接受 NULL 值。

有没有办法在执行上述查询之前检查列是否接受NULL 值...??

【问题讨论】:

标签: oracle11g


【解决方案1】:

您可以使用USER_TAB_COLUMNS 中的NULLABLE 列。这会告诉您该列是否允许使用二进制 Y/N 标志为空。

如果您想将其放入脚本中,您可以执行以下操作:

declare

   l_null user_tab_columns.nullable%type;

begin

   select nullable into l_null
     from user_tab_columns
    where table_name = 'CUSTOMER'
      and column_name = 'CUSTOMER_ID';

   if l_null = 'N' then
      execute immediate 'ALTER TABLE Customer 
                          MODIFY (Customer_ID nvarchar2(20) NULL)';
   end if;

end;

最好不要使用动态 SQL 来更改表。手动进行,并确保首先仔细检查所有内容。

【讨论】:

    【解决方案2】:

    或者你可以忽略错误:

    declare
        already_null exception;
        pragma exception_init (already_null , -01451);
    begin
        execute immediate 'alter table <TABLE> modify(<COLUMN> null)';
        exception when already_null then null;
    end;
    /
    

    【讨论】:

      【解决方案3】:

      如果您之前为 NOT NULL 列提供了 DEFAULT ON NULL 值,则可能会遇到此错误。

      如果是这种情况,要使列可以为空,您还必须在修改其可空性约束时将其默认值重置为 NULL

      例如:

      DEFINE table_name = your_table_name_here
      DEFINE column_name = your_column_name_here;
      
      ALTER TABLE &table_name
        MODIFY (
          &column_name
            DEFAULT NULL
            NULL
        );
      

      【讨论】:

        【解决方案4】:

        我做了这样的事情,效果很好。 尝试执行查询,如果有错误,捕捉SQLException

        try {
        stmt.execute("ALTER TABLE Customer MODIFY Customer_ID nvarchar2(20) NULL");
        } catch (SQLException sqe) {
        Logger("Column to be modified to NULL is already NULL : " + sqe);
        }
        

        这是正确的做法吗?

        【讨论】:

          【解决方案5】:

          修改现有表的约束

          例如...将not null 约束添加到列。

          然后按照给定的步骤操作:

          1) 选择要在其中修改更改的表。

          2) 点击Actions.. ---> 选择列 ----> 添加。

          3) 现在给出列名、数据类型、大小等,然后单击确定。

          4) 您将看到该列已添加到表中。

          5) 现在点击位于Actions 按钮左侧的Edit 按钮。

          6) 然后您将获得各种表格修改选项。

          7) 从列表中选择column

          8) 选择您要在其中提供not null 的特定列。

          9) 从column properties 中选择Cannot be null

          10) 就是这样。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2023-02-06
            • 2016-08-06
            • 2021-12-26
            • 2015-08-26
            • 2019-06-18
            • 1970-01-01
            • 2019-08-23
            • 2016-01-03
            相关资源
            最近更新 更多