Uniqueidentifier vs. IDENTITY vs. Material Code --which is the best choice for primary key?

前端 未结 4 1208
面向向阳花
面向向阳花 2021-02-02 13:41

Which one is the best choice for primary key in SQL Server?
There are some example code:

Uniqueidentifiers

e.g.

4条回答
  •  -上瘾入骨i
    2021-02-02 14:26

    GUIDs are large but have the advantage of being unique everywhere: this table or that, this server or that, if you have the GUID then everything else is knowable. If that is useful to you, then great, but you will pay for it in overhead, and continue to pay, and pay, and pay....

    Material codes only really work for smaller immutable keys, like colors or classification codes and the like. R will always be red, G will be green, it is one byte, etc.

    Identity columns come into their own when there may not be a material code, or the natural key is composed of several material codes together, or the natural key is already composed of other identity columns and/or GUIDs, or the natural key is mutable. Yes you could use a GUID but an integer column is much more efficient in all regards.

    Another option available in SQL 2012 are sequences, kind of like a database-level identity column. This is a nice halfway house between GUIDs and identity columns, in the sense that a sequence can be used across many tables, so that from a given value, not just the row is knowable, but the table too--but you can still use an INT or BIGINT (or SMALLINT!) if you think that will be enough for your data. That's kind of nifty for certain purposes, kind of like an object id in the OO world.

    Be aware that many or the light-weight ORMs expect tables to have a single column primary key, preferably an integer column, and may not play well with anything but an INT IDENTITY PK.

提交回复
热议问题