DeS*_*Ond 5 oracle triggers plsql sequence
我正在创建一个表格,我将添加文件名和许多其他字段.我使用fileid列按顺序表示文件; 即要上传的第一个文件应该有fieldid 1,然后下一个文件将有fileid 2,依此类推.我用了一个序列和触发器:
create sequence create_file_id start with 1 increment by 1 nocache;
Run Code Online (Sandbox Code Playgroud)
触发器是:
before insert on add_files_details
for each row
begin
select create_file_id.nextval into :new.file_id from dual;
end;
Run Code Online (Sandbox Code Playgroud)
但是,如果从表中删除任何记录/记录,则序列会混乱.所以,我正在考虑使用另一个带触发器的序列来减少前一个序列的值,删除的行数.但是我坚持实现这个序列的触发器.
序列:
create sequence del_file_id increment by -1 nocache;
Run Code Online (Sandbox Code Playgroud)
有没有实现这个目标?
您可以让序列执行主键作业并创建基表的视图,然后选择
rownum 作为要按顺序查看从1到N的数字的列:
SQL> create table your_table(
2 tab_id number primary key,
3 col number
4 )
5 ;
Table created
SQL> create sequence gen_id;
Sequence created
SQL> create trigger TR_PK_your_table
2 before insert on your_table
3 for each row
4 begin
5 :new.tab_id := gen_id.nextval; -- This kind of assignment is allowed in 11g
6 end; -- and higher, in version prior to 11g
7 / -- conventional select statement is used
Trigger created
SQL> insert into your_table(col)
2 select level
3 from dual
4 connect by level <=7;
7 rows inserted
SQL> commit;
Commit complete
SQL> select *
2 from your_table;
TAB_ID COL
---------- ----------
1 1
2 2
3 3
4 4
5 5
6 6
7 7
7 rows selected
SQL> create or replace view V_your_table
2 as
3 select tab_id
4 , col
5 , rownum as num
6 from your_table
7 ;
View created
SQL> select *
2 from v_your_table;
TAB_ID COL NUM
---------- ---------- ----------
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
7 rows selected
SQL> delete from your_table where tab_id in (3,5,6);
3 rows deleted
SQL> commit;
Commit complete
SQL> select *
2 from your_table;
TAB_ID COL
---------- ----------
1 1
2 2
4 4
7 7
SQL> select *
2 from v_your_table;
TAB_ID COL NUM
---------- ---------- ----------
1 1 1
2 2 2
4 4 3
7 7 4
SQL>
Run Code Online (Sandbox Code Playgroud)
小智 5
阅读AskTom,了解为什么你不想尝试创建无间隙序列.
@Nicholas在那里有一个非常好的方法,从来没有想到过.
但是,有几个问题.
尽管在方法上稍微扩展一下,可能会在表上添加DATE或TIMESTAMP列,然后在ORDER BY中使用它.我没有测试过这种方法.
回到AskTom的观点,是否有一个特定原因要求无间隙序列?
如果水管在房间的房间内突然爆裂,箱子就会进入,而且50个箱子在使用时完全彻底损坏.
或者有人意外地碾碎了一个盒子.
管他呢
一般而言,它不是无间隙的.它不是一个系统分配,无间隙序列......