Oracle:实现列自动管理

时间:2016-08-18 07:30:39

标签: oracle plsql

的dataSource:

username type rank
a        106  1
a        116  2
a        126  3
b        106  1
b        106  2

删除a时,116,2此记录返回:

username type rank
a        106  1
a        126  2
b        106  1
b        106  2

当插入a时,116返回:

username type rank
a        106  1
a        126  2
a        116  3
b        106  1
b        106  2

我选择使用跳跳器来实现:

刀片(成功):

create or replace trigger bi_auto
  before insert
  on auto 
  for each row
declare
  -- local variables here
begin
  select count(rank)+1 into :new.rank from auto where username=:new.username;
end bi_auto;

删除(失败,返回ora-04091,ora-06512,ora-04088):

create or replace trigger bd_auto
  after delete
  on auto 
  for each row
declare
  -- local variables here
begin
  insert into session_auto
  select username, type, rank() over(partition by username order by rank) ranknew from auto where username=:old.username order by username;
  delete from auto where username=:old.username;
  insert into auto select * from session_auto;
end bd_auto;

请帮我修改一下,谢谢。我知道性能有问题,但我想知道如何实现。

1 个答案:

答案 0 :(得分:0)

我认为整个方法存在问题且容易出错。动态计算排名要容易得多。如果您希望方便查询表,可以将其添加到视图中:

CREATE OR REPLACE VIEW auto_view AS
SELECT username, type, RANK() OVER (PARTITION BY username ORDER BY TYPE ASC) r
FROM   auto

如果性能 大问题,您可以随时materialize your view