When having an identity column is not a good idea?

后端 未结 8 429
深忆病人
深忆病人 2021-01-12 04:06

In tables where you need only 1 column as the key, and values in that column can be integers, when you shouldn\'t use an identity field?

To the contrary, in

相关标签:
8条回答
  • 2021-01-12 05:08

    If I need a surrogate, I would either use an IDENTITY column or a GUID column depending on the need for global uniqueness.

    If there is a natural primary key, or the primary key is defined as a unique combination of other foreign keys, then I typically do not have an IDENTITY, nor do I use it as the primary key.

    There is an exception, which is snapshot configuration tables which I am tracking with an audit trigger. In this case, there is usually a logical "primary key" (usually date of the snapshot and natural key of the row - like a cost center or gl account number for which the row is a configuration record), but instead of using the natural "primary key" as the primary key, I add an IDENTITY and make that the primary key and make a unique index or constraint on the date and natural key. Although theoretically the date and natural key shouldn't change, in these tables, if a user does that instead of adding a new row and deleting the old row, I want the audit (which reflects a change to a row identified by its primary key) to really reflect a change in the row - not the disappearance of a key and the appearance of a new one.

    0 讨论(0)
  • 2021-01-12 05:10

    I'm not sure I understand enough about your context, but I interpret your question to be:

    "If I need the database to create a unique column (for whatever reason), when shouldn't it be a monotonically increasing integer (identity) column?"

    In those cases, there's no reason to use anything other than the facility provided by the DBMS for the purpose; in your case (SQL Server?) that's an identity.

    Except:

    If you'll ever need to merge the table with data from another source, use a GUID, which will prevent duplicate keys from colliding.

    0 讨论(0)
提交回复
热议问题