Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MODIFY COLUMN in oracle - How to check if a column is nullable before setting to nullable?

I'm trying to fill in for a colleague in doing some Oracle work, and ran into a snag. In attempting to write a script to modify a column to nullable, I ran into the lovely ORA-01451 error:

ORA-01451: column to be modified to NULL cannot be modified to NULL 

This is happening because the column is already NULL. We have several databases that need to be udpated, so in my faulty assumption I figured setting it to NULL should work across the board to make sure everybody was up to date, regardless of whether they had manually set this column to nullable or not. However, this apparently causes an error for some folks who already have the column as nullable.

How does one check if a column is already nullable so as to avoid the error? Something that would accomplish this idea:

IF( MyTable.MyColumn IS NOT NULLABLE)    ALTER TABLE MyTable MODIFY(MyColumn  NULL); 
like image 534
Jay S Avatar asked Jun 22 '09 19:06

Jay S


People also ask

How do you check a column is nullable or not in Oracle?

Select Columnproperty(object_id('Schema. table','U'),'column','allowsnull'); But this is for SQL. Select is_nullable from sys. colmns where object_id = object_id('schema.

How do you change a column from not null to null in Oracle?

NOT NULL constraint specifies that a column cannot contain NULL values. To add a NOT NULL constraint to an existing table by using the ALTER TABLE statement. ALTER TABLE table_name MODIFY ( column_name NOT NULL); In this case, the column_name must not contain any NULL value before applying the NOT NULL constraint.

How do you change a column to nullable in Oracle?

1) Select the table in which you want to modify changes. 2) Click on Actions.. ---> select column ----> add. 3) Now give the column name, datatype, size, etc. and click ok.

How do you add NOT NULL constraints in existing columns?

To add not null constraint to an existing column in MySQL, we will use the ALTER command. This is a type of validation to restrict the user from entering null values.


1 Answers

You could do this in PL/SQL:

declare   l_nullable user_tab_columns.nullable%type; begin   select nullable into l_nullable   from user_tab_columns   where table_name = 'MYTABLE'   and   column_name = 'MYCOLUMN';    if l_nullable = 'N' then     execute immediate 'alter table mytable modify (mycolumn null)';   end if; end; 
like image 145
Tony Andrews Avatar answered Sep 16 '22 22:09

Tony Andrews