SQL语言——alter table

来源:互联网 发布:涤纶网络丝织带 编辑:程序博客网 时间:2024/04/28 12:45

alter table 

1.更改字段的类型:alter table  表名 modify(字段名 字段类型);

alter table student modify(age char(10));

2.更改表名:alter table 表名 rename to 新表名;

alter table student rename to re_student;

3.更改字段名:alter table 表名 rename column 字段名 to 新字段名;

alter table student rename column age to re_age;

4.增加字段:alter table 表名 add(字段名 字段类型);

alter table student add(note varchar2(200));

5.删除字段:alter table 表名 drop(字段名);

alter table student drop age;

6.增加约束:

alter table student add constraint pk_student primary key(id);

alter table student add constraint uc_student unique(id);

alter table student add constraint  fk_student foreign key(id_class)  references  class(id);

alter table student add constraint chk_student check(id>0);

7.删除约束:

alter table student drop constraint 约束名;

8.设置字段默认值:

alter table 表名 alter column 字段名 set default '默认值';

9.撤销default约束:alter table 表名 alter column 字段名 drop default;

10.增加视图

create view 视图名 as

select 字段名1,字段名2…… from 表名 where 字段名1<100;

11.撤销视图

drop view 视图名

12.增加索引

create index 索引名 on 表名(字段名);

create index idx_student on student(name);

13.撤销索引

drop index 索引名;

14.自增(oracle需创建序列)

create sequence stu_sequence

minvalue 1

start with 1

increment by 1

cache 10;

insert into student(id,age) values (stu_sequence.nextval,age);

15.oracle建表设置自增主键

--建表

create table student

( s_id number primary key,

 name char(10) not null

);


--建序列

create sequence stu_sequence

increment by 1

start with 1

nomaxvalue

nocycle

cache 10;


-- 建触发器

create or replace trigger stu_trigger    
before insert on student                 
for each row
declare
nextid number;
begin
IF:new.s_id IS NULL or:new.s_id=0 THEN                
select stu_sequence.nextval                                             
into nextid
from sys.dual;
:new.s_id:=nextid;
end if;
end stu_trigger; 


这样就可以了,插入数据测试:

insert into student(name) values('张三');