MS SQL datetime precision problem

后端 未结 7 1364
无人共我
无人共我 2021-01-05 11:37

I have a situation where two persons might work on the same order (stored in an MS SQL database) from two different computers. To prevent data loss in the case where one wou

相关标签:
7条回答
  • 2021-01-05 11:54

    YOu have to make sure your time precisions line up - this is mostly doable by having the proper logic on the C# side to actually reduce the precision under that which is native in the DateTime object - basically make suer you have for example timestamps always in Seconds, not lower, across all layers.

    If you do that properly, the timestamp across all layers will be immediately comparable.

    0 讨论(0)
  • 2021-01-05 11:56

    There is another way to do this potentially.

    Instead of passing in the "Last Saved" from the local machine, modify the UPDATE stored procedure. Assign LastSaved = getdate() Then return the value of LastSaved (and any other results, such as IDs), and update the LastSaved time at the client with that result.

    There are two obvious advantages to this. One is that your DateTime accuracy is preserved. The other is that the date and time are now consistent with the server, rather than suffering from any network latency and local clock drift issues.

    We usually use auto generated SPs for CRUD operations, and the tables usually run "Created/LastUpdated" and "CreatedBy/LastUpdatedBy" pairs where the dates are set on the server, and the "By" values are passed in, and if NULL are set to System_User

    0 讨论(0)
  • 2021-01-05 11:58

    Check the Compatibility Version to SQL 2014 - Change in SQL 2016 converts DateTime to DateTime2(7) in Entity Framework.

    see MSN.

    Try this SQL to Test on YourTable and YourDateTime column:

    select top 100 <YourDateTimeColumn> date1,
    cast(<YourDateTimeColumn> as datetime2(3)) date2,
    cast(<YourDateTimeColumn> as datetime2(7)) date3,
    case when <YourDateTimeColumn> <> cast(<YourDateTimeColumn> as datetime2(3)) 
       then 'unequal' else 'equal' end as datesareequal
    from <YourTableName>
    
    0 讨论(0)
  • 2021-01-05 12:00

    You could add an integer revision field to your order table. Every time a user saves the order you increase the revision by one. Then its easy to check if somebody has altered the order or if the user who wants to save the order are on the latest revision.

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

    I know you said you can't change the type, but if this is only to maintain compatibility & your using 2008 you could change the lastSaved field to DATETIME2 (which is fully compatible with DATETIME) and use SYSDATETIME() both of which have much greater precision.

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

    You could use a timestamp field to check last edit date rather than a datetime field? (In SQL 2008 this is now RowVersion)

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