2015-04-23 70 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