Skip to content

Queries involving DATETIME behave differently between SQL Server versions 2014 & 2016 #325

Closed

Description

@kalebpederson

We recently attempted to upgrade to SQL Server 2016 but ran into some problems wherein EntityFramework didn't take into account the differences in behaviors between SQL Server 2014 and SQL Server 2016. Here's the breaking changes list provided by Microsoft:

https://docs.microsoft.com/en-us/sql/database-engine/breaking-changes-to-database-engine-features-in-sql-server-2016

In that we read the following with respect to the DATETIME and DATETIME2 types:

Under database compatibility level 130, implicit conversions from datetime to datetime2 data types show improved accuracy by accounting for the fractional milliseconds, resulting in different converted values. Use explicit casting to datetime2 datatype whenever a mixed comparison scenario between datetime and datetime2 datatypes exists.

A full example that reproduces the issue is included in the following Gist (though note that the end off the file has the app.config values, schema, etc.):

https://gist.github.com/kalebpederson/4c4e8b6f8ff5574405bd9c5c362ec477

The crux of the issue is that EntityFramework generates a query which includes an implicit conversion between DATETIME and DATETIME2. The following query is one example that was generated when using a concurrency check on a DATETIME column:

exec sp_executesql N'UPDATE [dbo].[SampleObject]
SET [ModifiedAt] = @0
WHERE (([Id] = @1) AND ([ModifiedAt] = @2))
',N'@0 datetime2(7),@1 nvarchar(128),@2 datetime2(7)'
,@0='2017-07-21 16:35:06.3950601'
,@1=N'8fad0aa7-b517-4a16-9fe1-0592127560af'
,@2='2017-07-21 16:34:47.9270000'

The above query performs an implicit conversion between the ModifiedAt column of type DATETIME and the @2 parameter of type DATETIME2. However, the exact same issue can occur when performing a query that uses date time. The following code generates a query which has the identical problem:

var sample = context.Values.First(x => x.ModifiedAt == creationTime);

Although I couldn't find an issue similar to this in the EntityFramework repository, I have seen other reports of it online:

https://social.msdn.microsoft.com/Forums/silverlight/en-US/de5dbf3e-8c95-40f4-9e31-b71f1f31983d/change-in-datetime2-implementation-in-sql-server-2016?forum=transactsql

The original poster of the above forum post provided a query which can be run against SQL Server 2013 and SQL Server 2016 and which is useful in seeing the differences:

select 
datemodified date1,
cast(datemodified as datetime2(3)) date2,
cast(datemodified as datetime2(7)) date3,
case when datemodified <> cast(datemodified as datetime2(3)) 
 then 'unequal' else 'equal' end as datesareequal
from applicationsettings

The provided gist varies the accuracy by changing the digit that affects rounding so that we can see the behavior based on the last digit of the provided date time. Ideally the results of the tests that run against the sqlserver2013 server and the sqlserver2016 server will be identical once this is fixed.

Thank you for your support, and please don't hesitate to ask questions!

Activity

  1. ErikEJ commented on Jul 25, 2017

    @ErikEJ
    Contributor

    See #49 - closed as wont fix

  2. divega commented on Aug 2, 2017

    @divega
    Contributor

    @kalebpederson thanks for the detailed explanation! As @ErikEJ mentioned, this is a known issue that we have previously decided not to fix.

    At the core of the problem, EF is creating parameters of type DATETIME2 even for assignments or comparisons with columns of type DATETIME. This has a number of different consequences depending on the role of the column and whether it is encrypted.

    The workaround we are recommending to customers is to change the type of the column to be DATETIME2. This is something that we wish we could do in the product more automatically, e.g. Code First and Migrations should really be doing this, since DATETIME2 is a more appropriate type to map System.DateTime values, however we can't do it because it would have too many side effects on existing applications and the compatibility bar for newer versions of EF 6 is very high.

    Although I think we knew most of this when we previously decided not to fix the issue, the fact that more customers are hitting it constitutes new information.

    It would be great if you could provide:

    1. More concrete details about how your applications are being impacted (e.g. how many tables have this issue, what kind of operations performed by the application are failing, etc.)
    2. An assessment on whether you could apply the recommended workaround of changing the columns to DATETIME2.
  3. ajcvickers commented on Aug 14, 2017

    @ajcvickers
    Contributor

    EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.

    BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.

  4. kalebpederson commented on Aug 16, 2017

    @kalebpederson
    Author

    @divega Sorry, I didn't see your follow-up questions sooner.

    Responses to your questions:

    1. We currently have ~80 tables with a column where we would likely run into this issue, though we've seen it actually happen in far fewer cases. The main operation that is failing for us is the concurrency check on columns of type DATETIME that happen during update operations in our regression test runs. The result of the failed concurrency check is that no rows are updated and an exception is thrown. We could, in theory, run into the exact same issue on comparisons in 100s of tables and 1000s of columns, but since we're usually operating in a disconnected graph (or restoring state, doing updates, and committing), we haven't found any cases where we have the original, more-precise DateTime object around whose use would result in the failed comparison.

    2. After seeing the initial contributor-response, we started working through the analysis and since have updated the ~80 tables necessary and are planning on pushing those updates through our different environments if everything looks good.

    It may be worth noting that, despite our regression suites, we can't guarantee that we won't run into additional places that exhibit the problem. We have only proven that updating our concurrency columns from type DATETIME to DATETIME2 has resulted in successful regression runs and exploratory testing; regression runs, however, will not be identical in performance and timing characteristics to those of production. Migrating all our columns to guarantee that we don't have issues is a much bigger task.

  5. vinniep79 commented on Jun 6, 2018

    @vinniep79

    @divega Hello, I believe we just ran into this issue. We had a single table impacted (that we've seen, so far) in SQL Azure. We recently attempted updating the compatibility level of SQL server from 100 to 130, and one of our EF statements began failing with: "Store update, insert, or delete statement affected an unexpected number of rows (0). "

    After diving into the issue a little bit more it seems that indeed the EF query is using a DATETIME2 parameter but the underlying table has a DATETIME parameter.

    1. A single table, so far.
    2. I believe we can change the column type. I'll test this out tomorrow.
  6. DebduttaNath commented on Aug 8, 2018

    @DebduttaNath

    We just encountered the same problem. When I was looking for the solution, I reached to this page. Yes one solution is change the datatype of the field DATETIME to DATETIME2 in the table. But, this is not possible for us, because we have hundreds of tables.
    Another way to solve this, just add a CAST function with the parameter, like this. This will work.
    AND ([ModifiedAt] = CAST(@2 AS DATETIME)))
    Again, this has a huge impact on change. All the places where this comparison has been used, we have to change that.

  7. jzabroski commented on May 5, 2020

    @jzabroski

    I know this is an old issue, but @kalebpederson how is it possible you have a database running SQL Server 2013 when there is no such version listed? Any chance you can edit the title to say SQL Server 2014? #57 is also helpful. Just saying, half of us depend on Google to do our jobs correctly and efficiently.

  8. changed the title [-]Queries involving DATETIME behave differently between SQL Server versions 2013 & 2016[/-] [+]Queries involving DATETIME behave differently between SQL Server versions 2014 & 2016[/+] on May 6, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions