正 文

oracle中实现主键的自动增加


www.7dspace.com  更新日期:2005-8-17 3:01:23  七度空间


 

实现方法1:
建立一个最小为1,最大为nomaxvalue的一个序列号会自动循环的序列

create sequence 序列名
increment by 1
start with 1
nomaxvalue 
nocycle;

当向表中插入数据时,SQL语句写法如下:
SQL> insert into 表名 values(序列名.nextval,列1值,列2值, ...);
当要重用该序列号时,有两种方法:
a. 在同一个sql块中重用:
SQL>insert into表名(序列名.currval, 列1值,列2值...);
b. 在存储进程中,将该值取到一个参数中:
SQL>select序列名.nextval into 参数名 from dual;
然后在重用该序列号的地方调用这个参数。

实现方法2:(利用触发器)

SQL> create sequence a_sequence
  2  start with 1
  3  increment by 1;

序列已创建。

SQL> create table t (n number ,v varchar2(10));

表已创建。

SQL> create or replace trigger t_trg
  2  before insert or update on t
  3  for each row
  4  begin
  5    select a_sequence.nextval into :new.n from dual;
  6  end;
  7  /

触发器已创建

SQL> insert into t values(111,'ok');

已创建 1 行。

SQL> select *  from t;

         N V
---------- ----------
         1 ok


上一篇:ORACLE 8i,9i 表连接方法全介绍
下一篇:MySQL 查询中的分页思路的优化
作者:  来源:csdn ( 责任编辑:7dspace )
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐