2015-04-23 25 views
1

如果问题低于标准(基本上是最重要的),那么首先是应用。从自动递增的列中删除值

我有一列的值会根据其他列自动递增。例如:如果列name的值为"abc","abc" ,"xyz","xyz",xyz","hij"自动递增列中的值必须是"1","2","1","2","3","1"

删除或更新记录时发生问题。 如果有人删除价值"2"["xyz"]值怎么办? 如何处理这种情况?

回答

1

作为选项之一(简单直接),您可以创建一个视图并在每次查询视图时即时生成“自动递增列”。

下面是一个例子:

-- source table, which does not contain that auto incremented 
-- column you are interested in 
create table t1(id, col1) as (
    select 1, 'abc' from dual union all 
    select 2, 'abc' from dual union all 
    select 3, 'xyz' from dual union all 
    select 4, 'xyz' from dual union all 
    select 5, 'xyz' from dual union all 
    select 6, 'hij' from dual 
); 

-- and here is the view 
create or replace view t1_v as 
    select id 
     , col1 
     , row_number() over(partition by col1 
           order by id) as auto_inc 
    from t1; 


select * 
    from t1_v; 

     ID COL1 AUTO_INC 
---------- ---- ---------- 
     1 abc   1 
     2 abc   2 
     6 hij   1 
     3 xyz   1 
     4 xyz   2 
     5 xyz   3 

更新值:

-- Update can be issued against base table or 
-- a view, if it's a key-preserved one 
update t1 
    set col1 = 'acb' 
where id = 1; 

select * 
    from t1_v; 


     ID COL1 AUTO_INC 
---------- ---- ---------- 
     2 abc   1 
     1 acb   1 
     6 hij   1 
     3 xyz   1 
     4 xyz   2 
     5 xyz   3 

删除行:

-- You can delete from the base table or 
-- a view, if it's a key-preserved one 
delete from t1 
    where id = 4; 

select * 
    from t1_v; 

     ID COL1 AUTO_INC 
---------- ---- ---------- 
     2 abc   1 
     1 acb   1 
     6 hij   1 
     3 xyz   1 
     5 xyz   2 
+0

感谢这么慕Sir.Just一个问题,我当时就想,使用触发器...我可以使用它作为替代吗?只是一个问题,我更喜欢你的方法。 – vish1990

+0

@ vish1990是的,可以使用触发器。然后,“auto-inc”列必须是表的一部分,并且在删除或修改某些内容时应更新整个表。这不是一个可扩展的,更容易出错的方法。 –

+0

非常感谢主席先生 – vish1990