Database-wide unique-yet-simple identifiers in SQL Server

后端 未结 11 813
余生分开走
余生分开走 2020-12-12 12:50

First, I\'m aware of this question, and the suggestion (using GUID) doesn\'t apply in my situation.

I want simple UIDs so that my users can easily communicate this i

11条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-12 13:27

    I use a high/low algorithm for this. I can't find a description for this online though. Must blog about it.

    In my database, I have an ID table with an counter field. This is the high part. In my application, I have a counter that goes from 0 to 99. This is the low part. The generated key is 100 * high + low.

    To get a key, I do the following

    initially high = -1
    initially low = 0
    
    method GetNewKey()
    begin
      if high = -1 then
        high = GetNewHighFromDatabase
    
      newkey = 100 * high + low.
      Inc low
      If low = 100 then
        low = 0
        high = -1
    
      return newKey
    end
    

    The real code is more complicated with locks etc but that is the general gist.

    There are a number of ways of getting the high value from the database including auto inc keys, generators etc. The best way depends on the db you are using.

    This algorithm gives simple keys while avoiding most the db hit of looking up a new key every time. In testing, I found it had similar performance to guids and vastly better performance than retrieving an auto inc key every time.

提交回复
热议问题