将列修改为NULL - Oracle

Gok*_* KP 8 oracle11g

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

最初Customer_IDWILL NOT接受NULL值.

我已从代码级别进行了一些更改,因此默认情况下该Customer_ID列将接受NULL值.

现在我的要求是,我需要再次使这个列接受NULL值.

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

ALTER TABLE Customer MODIFY Customer_ID nvarchar2(20) NULL
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

ORA-01451 error, the column already allows null entries so
therefore cannot be modified
Run Code Online (Sandbox Code Playgroud)

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

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

Ben*_*Ben 12

您可以在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;
Run Code Online (Sandbox Code Playgroud)

最好不要使用动态SQL来改变表.手动完成并确保首先仔细检查所有内容.


gro*_*ter 5

或者您可以忽略该错误:

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;
/
Run Code Online (Sandbox Code Playgroud)