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条)

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮