----------------oracle自增字段 ,必须要序列和触发器
--如果seq_id不插入空值,但无重复 ,有记录之后再加唯一约束
drop table t_imp_test;
create table t_imp_test(
seq_id number(10),
name varchar2(200),
tel varchar2(200),
dw varchar2(200)
);
--如果seq_id预先有多个空值,但非空的值都不重复,能加唯一约束
insert into t_imp_test(name,tel,dw)
select 'aa' name,'13780001256' tel,'易方达基金公司' dw from dual
union all select 'bb' name,'' tel,'南方基金公司' dw from dual
union all select 'cc' name,'13780001248' tel,'博时基金公司' dw from dual
union all select 'dd' name,'13780008888' tel,'易方达基金公司' dw from dual
;
select * from t_imp_test;
commit;
---加约束
alter table t_imp_test add constraint const_t_imp_test_seq_id unique(seq_id);
--1.建序列
select count(1) from t_imp_test--4 开始值
;
--drop sequence seq_t_imp_test_id;
create sequence seq_t_imp_test_id
minvalue 1
maxvalue 9999999999
start with 5----4+1
increment by 1
nocache;
--触发器
create or replace trigger trig_t_imp_test_id
before insert on t_imp_test
for each row
begin
select seq_t_imp_test_id.nextval into :new.seq_id from dual;
end;
---修改 seq_id 的值
update t_imp_test t set t.seq_id=(
select rid from (
select a.rowid rowi,rownum rid from t_imp_test a
) where rowi=t.rowid
)
where exists(
select rid from (
select a.rowid rowi,rownum rid from t_imp_test a
) where rowi=t.rowid
);
select * from t_imp_test;
---测试
insert into t_imp_test(name,tel,dw)
select 'ee' name,'13780001259' tel,'易方达基金公司' dw from dual
union all select 'ff' name,'' tel,'南方基金公司' dw from dual
;
select * from t_imp_test; -------ok 序列从5开始
commit;