[小结]对比实现自动编号功能的几种方法

--自动编号:Oracle
建表
create table t1(autoid number(10) primary key,name char(4));
创建序列
create sequence seq_t1_autoid;
添加数据
insert into t1(autoid,name) values(seq_t1_autoid.nextval,'a');
insert into t1(autoid,name) values(seq_t1_autoid.nextVal,'b');
commit;

--思考:能不能实现一个与DBMS无关的自动编号方法?
insert into t1(autoid,name) select max(autoid)+1,'c' from t1;
insert into t1(autoid,name)  select max(autoid)+1,'d' from t1;
commit;

--改正:
insert into t1(autoid,name) select nvl(max(autoid),0)+1,'c' from t1;
insert into t1(autoid,name)  select nvl(max(autoid),0)+1,'d' from t1;
commit;


面试:如何在Oracle中实现与Mysql一样的自动编号:
解决:使用触发器

create table t1(autoid number(10) primary key);
create sequence seq_t1_autoid;
create or replace trigger tr_t1_autoid
before insert on Friend
for each row
begin
  select seq_t1_autoid.nextval into :new.autoid from dual;
end;

--测试:
insert into t1(name) values('a');
insert into t1(name) values('b');
commit;

select * from t1; 

autoid  name  
     1      a    
     2      b    
+--------+------+

你可能感兴趣的:(oracle,C++,c,mysql,面试)