sql alter table
Add , delete, and modify fields in ORACLE through SQL statements (alter table)
. tablename modify (column datatype [default value][null/not null],….);
syntax for deleting fields: alter table tablename drop (column); To
add, modify, or delete multiple columns, separate them with commas.
Example of using alter table to add, delete and modify a column.
Create a table structure:
create table test1
(id varchar2(20) not null);
add a field:
alter table test1
add (name varchar2(30) default 'anonymous' not null);
use one SQL statement to add three fields at the same time:
alter table test1
add (name varchar2(30) default 'anonymous' not null,
age integer default 22 not null,
has_money number(9,2)
);
modify a field
alter table test1
modify (name varchar2(16) default 'unknown');
another: the more formal writing is:
-- Add/modify columns
alter table TABLE_NAME rename column FIELD_NAME to NEW_FIELD_NAME;
delete a field
alter table test1
drop column name;
required Note that if there are already values in a column, an error will occur if you change the column width to be smaller than these values.
For example, earlier if we insert a value
insert into test1
values ('1', 'We love you');
and then modify the column: alter table test1
modify (name varchar2(8));
will get the following error:
ERROR at the Line 2:
ORA-01441: cannot reduce column length because some values are too large
-------------------------------- -------------
Advanced usage:
rename table
ALTER TABLE table_name RENAME TO new_table_name;
modify the name of the column
Syntax :
ALTER TABLE table_name RENAME COLUMN supplier_name to sname;
example:
alter table s_dept rename column age to age1;
attached: create a table with a primary key >>
create table student (
studentid int primary key not null,
studentname varchar(8),
age int);
1. Create a primary key constraint while creating a table
(1) Unnamed
create table student (
studentid int primary key not null,
studentname varchar(8),
age int);
(2) Named
create table students (
studentid int ,
studentname varchar( 8),
age int,
constraint yy primary key(studentid));
2. Delete the existing primary key constraint in the table
(1) No name
available SELECT * from user_cons_columns;
Find the primary key name in the table and get the primary key in the student table named SYS_C002715
alter table student drop constraint SYS_C002715;
(2) There is a name
alter table students drop constraint yy;
3. Add a primary key constraint to the
table alter table student add constraint pk_student primary key( studentid);
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=326131876&siteId=291194637
Recommended
Ranking