How to avoid a database race condition when manually incrementing PK of new row

后端 未结 7 2416
伪装坚强ぢ
伪装坚强ぢ 2020-12-19 08:12

I have a legacy data table in SQL Server 2005 that has a PK with no identity/autoincrement and no power to implement one.

As a result, I am forced to create new rec

7条回答
  •  独厮守ぢ
    2020-12-19 08:58

    Not being able to change database schema is harsh.

    If you insert existing PK into table you will get SqlException with a message indicating PK constraint violation. Catch this exception and retry insert a few times until you succeed. If you find that collision rate is too high, you may try max(id) + instead of max(id) + 1. Note that with this approach your ids will have gaps and the id space will be exhausted sooner.

    Another possible approach is to emulate autoincrementing id outside of database. For instance, create a static integer, Interlocked.Increment it every time you need next id and use returned value. The tricky part is to initialize this static counter to good value. I would do it with Interlocked.CompareExchange:

    class Autoincrement {
      static int id = -1;
      public static int NextId() {
        if (id == -1) {
          // not initialized - initialize
          int lastId = 
                            
        
    提交评论

提交回复
热议问题