Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1888440
  • 博文数量: 606
  • 博客积分: 9991
  • 博客等级: 中将
  • 技术积分: 5725
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-17 19:07
文章分类

全部博文(606)

文章存档

2011年(10)

2010年(67)

2009年(155)

2008年(386)

分类: 数据库开发技术

2010-04-23 17:12:43

第一种方法:一般来说需要新建一个触发器(TRIGGER),使得在插入数据之前先运行Sequence生成自增号。

  1、建用户数据表
      drop table dectuser;
      create table dectuser(
           userid integer primary key,  /*
主键,自动增加*/
           name varchar2(20),
           sex varchar2(2)
           );2
、创建自动增长序列
      drop sequence dectuser_tb_seq;
      create sequence dectuser_tb_seq minvalue 1 maxvalue 99999999
               increment by 1
               start with 1;   /*
步长为1*/
3
、创建触发器
      create or replace trigger dectuser_tb_tri
          before insert on dectuser     /*
触发条件:当向表dectuser执行插入操作时触发此触发器*/
          for each row                       /*
对每一行都检测是否触发*/
          begin                                  /*
触发器开始*/
                 select dectuser_tb_seq.nextval into :new.userid from dual;   /*
触发器主题内容,即触发后执行的动作,在此是取得序列dectuser_tb_seq的下一个值插入到表dectuser中的userid字段中*/
          end;
   
          /                                        /*
退出sqlplus行编辑*/
4
、提交
      commit;
 
      
现在就完成了自增主键的设定,搞定!可以检测一下。
      insert into dectuser(name,sex) values ('wang','
');

     
提示已创建一行,表示成功。呵呵:D

     
要注意的是主键数据类型如果为number,则触发器创建不了

 

第二种方法:可以在插入数据时直接调用。

  insert into table(id,name) values(seq_name.nextval,'名字');

  其它:对于hibernate来说,在插入数据之前会先运行一次Sequence生成id的,所以这时如果还有触发器(TRIGGER),又要再运行一次Sequence,于是就会发现id是以2为步进增加的。这时把Trigger删除,步进就为1了。

 

1MySQL的自增变量是比较好记的,使用AUTO_INCREMENT关键字,如果知道英文的就容易记忆了,如下创建一个带有自增变理的表:

create table test(id int AUTO_INCREMENT

primary key not null,name varchar(50));

注释:此处的id一定要申明为主键,否则会报错。

2SQl Server使用identity关键字,可以很容易指定从什么数开始,增幅是多少,如下:

create table test(id int identity(100,10)

primary key not null,name varchar(50));

3Oracle不能够在创建表的时候指定自动关键字,它需要重新创建sequence,然后以"创建键.nextval"来引用:

create table test(id int primary key

not null,name varchar(50));

create sequence test_id(最好是表名+序列号标记)

increment by 1 start with 1 maxvalue 9999;

引用如下:

 

insert into test(test_id.nextval,'www');

 

 

 

阅读(1266) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~