📅  最后修改于: 2023-12-03 15:18:08.194000             🧑  作者: Mango
The ALTER TABLE
statement in Oracle is used to modify the structure of an existing table in a database. It allows programmers to add, modify, or delete columns, constraints, and other table attributes.
The basic syntax for altering a table in Oracle is as follows:
ALTER TABLE table_name
tabe_action;
Here, table_name
is the name of the table you want to modify, and table_action
is the specific alteration you want to perform on the table.
To add new columns to an existing table, you can use the ADD
keyword:
ALTER TABLE table_name
ADD (column_name1 datatype1 [DEFAULT expression],
column_name2 datatype2 [DEFAULT expression],
...);
Each column is specified with a name and a data type. Additionally, you can specify a default value for the column using the DEFAULT
keyword followed by an expression.
If you need to modify the data type or size of a column, you can use the MODIFY
keyword:
ALTER TABLE table_name
MODIFY column_name datatype [DEFAULT expression];
This statement allows you to change the data type and optionally assign a default value for the column.
To rename an existing column in a table, you can use the RENAME COLUMN
keyword:
ALTER TABLE table_name
RENAME COLUMN old_column_name TO new_column_name;
This allows you to change the name of a specific column in a table.
To remove one or more columns from a table, you can use the DROP COLUMN
keyword:
ALTER TABLE table_name
DROP COLUMN column_name;
You can specify multiple columns to be dropped by separating them with commas.
To add constraints to an existing table, such as primary key, unique, or foreign key constraints, you can use the ADD CONSTRAINT
keyword:
ALTER TABLE table_name
ADD CONSTRAINT constraint_name constraint_definition;
Here, constraint_name
is the name you assign to the constraint, and constraint_definition
is the specific constraint you want to add.
If you need to modify an existing constraint, such as changing the constraint condition or disabling/enabling it, you can use the MODIFY CONSTRAINT
keyword:
ALTER TABLE table_name
MODIFY CONSTRAINT constraint_name constraint_definition;
This statement allows you to alter the definition of an existing constraint. Note that only certain constraint types can be modified in Oracle.
To remove constraints from an existing table, you can use the DROP CONSTRAINT
keyword:
ALTER TABLE table_name
DROP CONSTRAINT constraint_name;
This statement allows you to drop a specific constraint from a table.
The ALTER TABLE
statement in Oracle provides various operations to modify the structure of existing tables. It allows you to add, modify, or drop columns, as well as add, modify, or drop constraints. Understanding how to use ALTER TABLE
is essential for effectively managing database schema changes.