Oracle增加修改删除字段/主键
发布时间:2020-12-12 15:46:41 所属栏目:百科 来源:网络整理
导读:修改字段名称 alter table xgj rename column old_name to new_name; 修改字段类型 alter table tablename modify (column datatype [ default value ][ null/not null ],….); 栗子 假设表xgj,有一个字段为name,数据类型char(20)。 create table xgj( id
修改字段名称alter table xgj rename column old_name to new_name;
修改字段类型alter table tablename modify (column datatype [default value][null/not null],….);
栗子假设表xgj,有一个字段为name,数据类型char(20)。 create table xgj( id number(9),name char(20) )
1、假设字段数据为空,则不管改为什么字段类型,可以直接执行:SQL> select * from xgj ;
ID NAME
---------- --------------------
SQL> alter table xgj modify(name varchar2(20));
Table altered
SQL>
2、假设字段有数据,则改为varchar2(20)可以直接执行:--紧接着第一个情况操作,将name的类型改为创建时的char(20)
SQL> alter table xgj modify(name char(20));
Table altered
--插入数据
SQL> insert into xgj(id,name) values (1,'xiaogongjiang');
1 row inserted
SQL> select * from xgj;
ID NAME
---------- --------------------
1 xiaogongjiang
SQL> alter table xgj modify(name varchar2(20));
Table altered
SQL> desc xgj;
Name Type Nullable Default Comments
---- ------------ -------- ------- --------
ID NUMBER(9) Y
NAME VARCHAR2(20) Y
SQL> alter table xgj modify(name varchar2(40));
Table altered
SQL> alter table xgj modify(name char(20));
Table altered
3、假设字段有数据,当修改后的类型和原类型不兼容时 ,执行时会弹出:“ORA-01439:要更改数据类型,则要修改的列必须为空”栗子: --建表
create table xgj (col1 number,col2 number) ;
--插入数据
insert into xgj(col1,col2) values (1,2);
--提交
commit ;
--修改col1 由number改为varchar2类型 (不兼容的类型)
alter table xgj modify ( col1 varchar2(20))
解决办法:
alter table xgj rename column col1 to col1_tmp;
alter table xgj add col1 varchar2(20);
update xgj set col1=trim(col1_tmp);
alter table xgj drop column col1_tmp;
总结: 添加字段alter table tablename add (column datatype [default value][null/not null],….);
使用一个SQL语句同时添加多个字段: alter table xgj add (name varchar2(30) default ‘无名氏’ not null,age integer default 22 not null,salary number(9,2) );
删除字段alter table tablename drop (column);
创建带主键的表create table student ( studentid int primary key not null,studentname varchar(8),age int);
1、创建表的同时创建主键约束 create table student ( studentid int primary key not null,age int);
(2)有命名 create table students ( studentid int,age int,constraint yy primary key(studentid));
2、删除表中已有的主键约束 alter table student drop constraint SYS_C002715;
(2)有命名 alter table students drop constraint yy;
3、向表中添加主键约束 alter table student add constraint pk_student primary key(studentid); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |