SQL Server - Guid VS. Long

后端 未结 7 1816
野的像风
野的像风 2020-12-29 00:06

Up until now i\'ve been using the C# \"Guid = Guid.NewGuid();\" method to generate a unique ID that can be stored as the ID field in some of my SQL Server database tables us

7条回答
  •  春和景丽
    2020-12-29 01:03

    You can debate GUID or identity all day. I prefer the database to generate the unique value with an identity. If you merge data from multiple databases, add another column (to identify the source database, possibly a tinyint or smallint) and form a composite primary key.

    If you do go with an identity, be sure to pick the right datatype, based on number of expected keys you will generate:

    bigint - 8 Bytes - max positive value: 9,223,372,036,854,775,807  
    int    - 4 Bytes - max positive value:             2,147,483,647
    

    Note "number of expected keys " is different than the number of rows. If you mainly add and keep rows, you may find that an INT is enough with over 2 billion unique keys. I'll bet your table won't get that big. However, if you have a high volume table where you keep adding and removing rows, you row count may be low, but you'll go through keys fast. You should do some calculations to see how log it would take to go through the INTs 2 billion keys. If it won't use them up any time soon go with INT, otherwise double the key size and go with BIGINT.

提交回复
热议问题