一、Oracle创建主键自增表(加序列-->加触发器)
1、创建表
create table Test_Increase(
userid number(10) NOT NULL primary key, /*主键,自动增加*/
username varchar2(20)
);
2、创建自动增长序列
CREATE SEQUENCE TestIncrease_Sequence
INCREMENT BY 1 -- 每次加几个
START WITH 1 -- 从1开始计数
NOMAXVALUE -- 不设置最大值 ,设置最大值:maxvalue 9999
NOCYCLE -- 一直累加,不循环
CACHE 10;
3、创建触发器
CREATE TRIGGER Test_Increase BEFORE
insert ON Test_Increase FOR EACH ROW /*对每一行都检测是否触发*/
begin
select TestIncrease_Sequence.nextval into:New.userid from dual;
end; /*退出sqlplus行编辑*/
4、提交
commit;
5、测试
添加字段的语法:alter table tablename add (column datatype [default value][null/not null],….);
修改字段的语法:alter table tablename modify (column datatype [default value][null/not null],….);
删除字段的语法:alter table tablename drop (column);
添加、修改、删除多列的话,用逗号隔开。
如:alter table test1
add (name varchar2(30) default ‘无名氏' not null,
age integer default 22 not null,
has_money number(9,2)
);
1、创建表
create table Test_Increase(
userid number(10) NOT NULL primary key, /*主键,自动增加*/
username varchar2(20)
);
2、创建自动增长序列
CREATE SEQUENCE TestIncrease_Sequence
INCREMENT BY 1 -- 每次加几个
START WITH 1 -- 从1开始计数
NOMAXVALUE -- 不设置最大值 ,设置最大值:maxvalue 9999
NOCYCLE -- 一直累加,不循环
CACHE 10;
3、创建触发器
CREATE TRIGGER Test_Increase BEFORE
insert ON Test_Increase FOR EACH ROW /*对每一行都检测是否触发*/
begin
select TestIncrease_Sequence.nextval into:New.userid from dual;
end; /*退出sqlplus行编辑*/
4、提交
commit;
5、测试
insert into Test_Increase(Username) values('test');
二、表字段的添加、修改、删除添加字段的语法:alter table tablename add (column datatype [default value][null/not null],….);
修改字段的语法:alter table tablename modify (column datatype [default value][null/not null],….);
删除字段的语法:alter table tablename drop (column);
添加、修改、删除多列的话,用逗号隔开。
如:alter table test1
add (name varchar2(30) default ‘无名氏' not null,
age integer default 22 not null,
has_money number(9,2)
);
三、外键
alter table test1 add constraint pk_id primary key(id);//设置父表中被用作字表外键的字段为主键
alter table test1 add foreign key (name_id) references test1 (id);//添加外键