您的位置:首页 > 数据库 > Oracle

Oracle增加修改删除字段/主键

2016-11-04 23:20 531 查看

修改字段名称

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))




解决办法:

修改原字段名col1 为col1 _tmp

alter table xgj rename column col1  to col1_tmp;


增加一个和原字段名同名的字段col1

alter table xgj add col1 varchar2(20);


将原字段col1_tmp数据更新到增加的字段col1

update xgj  set col1=trim(col1_tmp);


更新完,删除原字段col1_tmp

alter table xgj drop column col1_tmp;


总结:

1、当字段没有数据或者要修改的新类型和原类型兼容时,可以直接modify修改。

2、当字段有数据并用要修改的新类型和原类型不兼容时,要间接新建字段来转移。

添加字段

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、创建表的同时创建主键约束

(1)无命名

create table student (
studentid int primary key not null,
studentname varchar(8),
age int);


(2)有命名

create table students (
studentid int ,
studentname varchar(8),
age int,
constraint yy primary key(studentid));


2、删除表中已有的主键约束

(1)无命名

可用
SELECT * from user_cons_columns;


查找表中主键名称得student表中的主键名为SYS_C002715

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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: