Add a new column to a table with records and specify not null to report a ORA-01758. What should I do?
1. Specify the default value for the newly added column.
2. Clear the records in the table and add new columns.
The experiment is as follows:
- SQL> drop table ord;
- Table dropped
- SQL> create table ORD
- 2 (
- 3 ORD_NO NUMBER (2) notNull,
- 4 ORD_DATE DATE,
- 5 CUST_ID NUMBER (4)
- 6 );
- Table created
- SQL> insert into ORD values (1, sysdate, 100 );
- 1 row inserted
- SQL> COMMIT;
- Commit complete
- -- The table contains records, adds new columns, and specifies notNullTimes ORA-01758
- SQL> ALTER TABLE ORD ADD price NUMBER (8, 2) NOT NULL;
- Alter table ord add price NUMBER (8, 2) NOT NULL
- ORA-01758: The table must be empty to add required (not null) Columns
- -- Specify the default value for the new column, which can be added.
- SQL> ALTER TABLE ORD ADD price NUMBER (8, 2) DEFAULT 0 NOT NULL;
- Table altered
- -- Clear the records in the table without specifying the default value. This method is rarely used.
- SQL> TRUNCATE TABLE ORD;
- Table truncated
- SQL> alter table ORD drop column PRICE;
- Table altered
- SQL> ALTER TABLE ORD ADD price NUMBER (8, 2) NOT NULL;
- Table altered
- SQL>