Auto increment primary key

1. Let's say we have a table called "test" with two columns, id and testdata. (This is just a dumb quick example, so I won't bother to specify any constraints on id.)

create table test (id number, testdata varchar2(255));

2. Next we'll create a sequence to use for the id numbers in our test table.

create sequence test_seq
start with 1
increment by 1
nomaxvalue;

You could change "start with 1" to any number you want to begin with (e.g. if you already have 213 entries in a table and you want to begin using this for your 214th entry, replace with "start with 214"). The "increment by 1" clause is the default, so you could omit it. You could also replace it with "increment by n" if you want it to skip n-1 numbers between id numbers. The "nomaxvalue" tells it to keep incrementing forever as opposed to resetting at some point. i (I'm sure Oracle has some limitation on how big it can get, but I don't know what that limit is).

3. Now we're ready to create the trigger that will automatically insert the next number from the sequence into the id column.

create trigger test_trigger
before insert on test
for each row
begin
select test_seq.nextval into :new.id from dual;
end;
/

Greg Malewski writes:

You've demonstrated an implementation using triggers. This is not necessary, since instead it can be included as part of the INSERT statement. Using your example, my INSERT statement would be:


insert into test values(test_seq.nextval, 'voila!');


Here are a couple of questions the above might raise. This is pretty intuitive stuff, but I'm aiming it at the Oracle newbie since no expert would be reading this page anyway.

How do you tell what sequences and triggers are already out there?

select sequence_name from user_sequences;
select trigger_name from user_triggers;

How do you get rid of a sequence or trigger you created?

drop sequence test_seq;
drop trigger test_trigger;

Again, replace test_seq and test_trigger with the specific names you used. You can also keep the trigger but disable it so it won't automatically populate the id column with every insert (and enable it again later if you want):

alter trigger test_trigger disable;
alter trigger test_trigger enable;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值