drudfe0446838 2012-04-05 17:06 采纳率: 0%
浏览 57
已采纳

防止在oracle数据库中两次插入相同的值

I have a number which is in this form : 2012-01 (2012 as current year) and 01 is just a the maximum value of a field in my database incremented by 1, and each year that number is reset to 0.

but if there are two users that try to do the same operation at the same time the value is the same for both and thus i get the same number inserted twice in my database .

I thought of creating a sequence but that requires a job that resets the sequence each year and i would prefer if there is a way to make a lock before i get the next number and release it after an insert is done ?

Thanks.

  • 写回答

2条回答 默认 最新

  • duanji5116 2012-04-05 19:30
    关注

    You don't specify where you store the field that is used as the counter. But maybe it is possible to use a SELECT FOR UPDATE statement.

    Before you increment the value of your counter field by 1 you can lock that record by using a SELECT FOR UPDATE. Then update the counter.

    Something like this, assuming the table has only 1 record:

    SELECT *  
    FROM   CounterTable
    FOR UPDATE;
    
    UPDATE CounterTable
    SET    Counter = Counter + 1;
    
    COMMIT;
    

    If one session (user) has done the SELECT FOR UPDATE and not yet committed or rolled back, the other session (user) doing a SELECT FOR UPDATE will block waiting to be able to get a lock. This prevents two users from getting the same number.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助