When having an identity column is not a good idea?

后端 未结 8 428
深忆病人
深忆病人 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 04:44

    If you need to merge databases it's a lot easier if you don't have to regenerate keys.

    0 讨论(0)
  • 2021-01-12 04:45

    I recently implemented a Suffix Trie in C# that could index novels, and then allow searches to be done extremely fast, linear to the size of the search string. Part of the requirements (this was a homework assignment) was to use offline storage, so I used MS SQL, and needed a structure to represent a Node in a table.

    I ended up with the following structure : NodeID Character ParentID, etc, where the NodeID was a primary key.

    I didn't want this to be done as an autoincrementing identity for two main reasons.

    1. How do I get the value of a NodeID after I add it to the database/data table?
    2. I wanted more control when it came to generating my own IDs.
    0 讨论(0)
  • 2021-01-12 04:46

    If you already settled on the surrogate side of the Great Primary Key Debacle then I can't find a single reason not use use identity keys. The usual alternatives are guids (they have many disadvatages, primarily from size and randomness) and application layer generated keys. But creating a surrogate key in the application layer is a little bit harder than it seems and also does not cover non-application related data access (ie. batch loads, imports, other apps etc). The one special case is distributed applications when guids and even sequential guids may offer a better alternative to site id + identity keys..

    0 讨论(0)
  • 2021-01-12 04:55

    You cannot (normally) specify values when inserting into identity columns, so for example if the column "id" was specified as an identify the following SQL would fail:

    INSERT INTO MyTable (id, name) VALUES (1, 'Smith')
    

    In order to perform this sort of insert you need to have IDENTITY_INSERT on for that table - this is not intended to be on normally and can only be on for a maximum of 1 tables in the database at any point in time.

    0 讨论(0)
  • 2021-01-12 04:57

    I suppose if you are creating a many-to-many linking table, where both fields are foreign keys, you don't need an identity field.

    Nowadays I imagine that most ORMs expect there to be an identity field in every table. In general, it is a good practice to provide one.

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

    One case of not wanting an identity field would be in a one to one relationship. The secondary table would have as its primary key the same value as the primary table. The only reason to have an identity field in that situation would seem to be to satisfy an ORM.

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