Sql Server using DateTime as Primary Key

前端 未结 4 1952
被撕碎了的回忆
被撕碎了的回忆 2021-01-02 00:10

Hi my questions is similar to:

MySQL: Using DATETIME as primary key

But I\'m specifically interested in Sql Server and I want to approach the question practi

相关标签:
4条回答
  • 2021-01-02 00:26

    Yes you can, but it sounds like a very bad idea to me. If you are really worried about performance, you can use a sequential unique identifier, an auto-incrementing integer, or you can give the DateTime column its own clustered index (recommended).

    0 讨论(0)
  • 2021-01-02 00:34

    If you really want to avoid a surrogate key for this (ID/identity column), I would at least combine the datetime column with the user id column for a composite key. This sounds like a more natural fit for your data.

    0 讨论(0)
  • 2021-01-02 00:40

    In SQL Server 2008, use DATETIME2, not DATETIME. You can achieve upto 100 nanosecond precision in SQL Server 2008.

    If you sometimes need to record more than one row for a given time, however infrequently, then I'm not sure what you are trying to achieve by making the date and time into a key. Important criteria for choosing keys are Familiarity, Simplicity and Stability. On that basis, assuming it does make sense for your requirements, a date and time seems like a sensible choice.

    0 讨论(0)
  • 2021-01-02 00:51

    In order for infrequent collisions to be acceptable you really cannot use the timestamp as there will be collisions.

    You could code around collisions by using a smart procedure that modifies the datatime slightly, but why bother when an index on the timestamp would suffice and be far easier to implement.

    This article is informative on precision issues specific to C# however.

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