Repository navigation
Description
Describe the bug
It seems like DATETIME2 sql server datatype is not fully or correctly implemented in SqlDataReader.
using method GetDateTime - it handles DATETIME2 correctly
using method GetSqlDateTime - it throws an
System.InvalidCastException:
Exception message: Specified cast is not valid
Stack trace: at Microsoft.Data.SqlClient.SqlBuffer.get_SqlDateTime()
To reproduce
[TestMethod]
public void DateTime2Mapping()
{
string Statement = $@"SELECT CAST('2020-12-11 09:17:12.123456' AS DATETIME2) AS [MyDate]";
var builder = new SqlConnectionStringBuilder()
{
InitialCatalog = "master",
DataSource = @"any sql connection",
IntegratedSecurity = true,
};
var sqlConnection = new SqlConnection(builder.ConnectionString);
sqlConnection.Open();
using (SqlCommand command = new SqlCommand(Statement))
{
command.CommandType = CommandType.Text;
command.Connection = sqlConnection;
command.CommandText = Statement;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
var dtColDate = reader.GetSqlDateTime(0);
Assert.IsFalse(dtColDate.IsNull);
Console.WriteLine(dtColDate.Value);
}
}
}
}Expected behavior
I expect that GetSqlDateTime handles DATETIME2 and returns a SqlDateTime struct
Further technical details
Microsoft.Data.SqlClient version: 2.1.0
.NET target: Framework 4.7.2
SQL Server version: 15.0.4079.3 (2019)
Operating system: Windows 10
Additional context
Why I found this issue, is because I was profiling our code and saw that SqlDataReader.IsDbNull took up a lot of time since we need to check every column for null, since GetXX methods does not handle DBNull - and then I found SqlDataReader.GetSqlXX methods which handles DBNull.
Basically trying to get rid of the overhead in SqlDataReader
override public bool IsDBNull(int i)
{
{
CheckHeaderIsReady(columnIndex: i);
SetTimeout(_defaultTimeoutMilliseconds);
ReadColumnHeader(i); // header data only
}
return _data[i].IsNull;
}by swithing to
The IsNull property in the SqlTypes
i.e.
public bool IsNull => !this.m_fNotNull;Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsBacklog
Activity
JRahnama commentedon Dec 12, 2020
@bjornbouetsmith
DateTime2cannot be casted asSqlDateTime. The source of the issue comes from the difference in DateTime2 and SqlDateTime. I tested some changes in the driver to convert the dates and since the DateTime2 Range is from 0001-01-01 through 9999-12-31 to an accuracy of 100 nanoseconds and SqlDateTime Range is January 1, 1753 to December 31, 9999 to an accuracy of 3.33 milliseconds and there is no exact conversion in C# to do so I got wrong results. TheSqlDateTimeproperty inSqlBufferinside the driver casts the value toSqlDateTimeand that throws the exception, However you can get the value usingGetDateTimewith no problem. In addition, the casting can happen in server side or in your command as explainedhere.bjornbouetsmith commentedon Dec 12, 2020
Hi,
That might be true, but then you need a corresponding .NET struct that supports the extended range, i.e. a SqlDateTime2.
Right now the support for DATETIME2 is by my opinion only partially implemented, since there are a lot of advantage to using the GetSqlXX methods instead of using the GetXX methods.
The former do not throw exceptions if the column is NULL, GetXX methods do - so I would still suggest that you either "Fix" SqlDateTime to handle the extended range of DATETIME2 - or implement a SqlDateTime2 to handle the DATETIME2 and then naturally add a GetSqlDateTime2 method.
When reading millions of rows from the database where every single column can be null, it is a major performance degredation to use GetXX methods instead of GetSqlXX methods, since you need to check every single column on ever single row with first IsDBNull and then do something depending on the return value. With GetSqlXX methods they never fail because the row is null and you can call the IsNull property directly on the return value, which is a more than an order of 10 times faster because of the overhead in IsDBNull.
Most of the code to handle DATETIME2 is already implemented in GetDateTime, so it should be only a matter of either implementing a GetSqlDateTime2 or fixing GetSqlDateTime to handle the extra range by extending SqlDateTime.
I would prefer you implemented a GetSqlDateTime2 - since that would complete the API, since there is a DATETIME2 data type in the database without a corresponding Sql class in .NET. Which would probably require adding a SqlDateTime2 property to the SqlBuffer struct.
I will be happy to submit a pull request to this effect.
And casting to DateTime is not really an option on the SQL server, since that would truncate the precision.
ErikEJ commentedon Dec 12, 2020
There are APIs to get the nullability from a reader before calling the get methods, so you can avoid calling IsDbNull
bjornbouetsmith commentedon Dec 12, 2020
@ErikEJ What API is that?
SqlDataReader.IsDbNull is what I am using, and that is not performant, since it does a lot of checks.
And I need to call for each field on every row, so I have found no API, except SqlDataReader.IsDbNull, Convert.IsDbNull and the IsNull property of the SqlXX types.
Convert.IsDbNull is useless, since that will BOX any value type, which will cause garbage, SqlDataReader is a performance HOG because it needs to check for the correct state of the reader before accessing the field. Which unless I have missed something leaves me with the IsNull property of the SqlXX types.
I am not interested in an API that can tell me whether or not a column "can" be null - I already know ALL columns can be null, but a performant way to check if any field is null.
ErikEJ commentedon Dec 12, 2020
GetColumnSchema or GetSchemaTable
bjornbouetsmith commentedon Dec 12, 2020
@ErikEJ Yes, but that will only tell me the schema of the table, which I don't need and cannot use - I already know all columns can be null - I need to handle null values because SqlClient will throw exception if the field is null. Where the GetSqlXX methods will not throw exceptions, but instead return a struct with a IsNull property. So the only real way to manage null values if you care about performance and garbage collections.
Wraith2 commentedon Dec 13, 2020
Can you provide an isolated test case that exhibits the behaviour you see around null checks and direct type access causing more garbage than using the sql types. I've always assumed when working on the internals that the sql types would be more costly to use but if they're not I can investigate if there are ways to equalize the performance of the paths.
bjornbouetsmith commentedon Dec 14, 2020
@Wraith2 I never said my issue was around garbage - but only with performance, since the SqlClient is missing a SqlDateTime2 or equivalent class to represent DATETIME2.
if you use DATETIME2 - you are forced to use SqlDataReader.GetDateTime - and since that method does not gracefully handle null, you are then forced to first call SqlDataReader.IsDbNull.
The codepath for IsDbNull does a lot of work, which is required because it needs to check if the state is correct to be able to check for null. And then it ends up by accessing a property on SqlBuffer which is basically just a field accessor telling it whether or not data is null. If there was a SqlDateTime2 struct/GetSqlDateTime2, I would not have to call SqlDataReader.IsDbNull and then GetSqlDateTime - I could just use the performant way of just retrieving the SqlDateTime2 struct and call the IsNull property and if false, return the data contained in the struct.
using my "testcase" from above - I am sure you will be able to see the issue running this code below.
Of course the code below is silly, but imagine it being a 200 column row all having the possiblity of null and having 50k rows.
roji commentedon Dec 14, 2020
@bjornbouetsmith
Is this something you're actually seeing in production, or have benchmarked? Because a quick benchmark seems to show that the perf of GetSqlDateTime is the same as IsDBNull + GetDateTime (see below). After all, I'd expect GetSqlDateTime to have to do more or less the same null checking internally as you're doing externally when calling GetDateTime.
Benchmark results:
Benchmark code
ErikEJ commentedon Dec 14, 2020
Should it not be:
bjornbouetsmith commentedon Dec 14, 2020
@ErikEJ Yes that would have been great - except using GetSqlDateTime does not support DATETIME2 - which is my whole problem.
bjornbouetsmith commentedon Dec 14, 2020
@roji Yes I have profiled this and could see that IsDbNull was the method using the most time.
And I have no idea how that benchmark you made runs, but if you call ExecuteReader, and only read one field from that reader, the isolated performance of IsDbNull will drown in the connection overhead etc.
So I would suggest if you want to test like that, that you open the reader once, and then call reader.IsDbNull/GetDateTime 10million times inside a loop and do the same with GetSqlDateTime.
that would give you the performance testing in question - and only measure the time of reader.IsDbNull/GetDateTime - not the time it takes to open the connection and execute the query.
Using this simple test shows a huge performance difference on my machine:
IsDbNull:00:00:04.1302114
GetSqlDateTime:00:00:02.6796905
IsDbNull:00:00:04.1251925
GetSqlDateTime:00:00:02.7111852
And reading 10million+ very wide rows where all fields can be null for performance reasons, then yes it makes a big difference.
I considered "fixing" the issue by making my stored procedure use ISNULL, but that would defeat the purpose of having null for performance reasons, since then suddenly the sql server would have to transfer a value instead of just a bit stating the field was null - so we would use more bandwith/time just reading the data. So I am still convinced that having a GetSqlDateTime method that either handles DATETIME2 - or having a GetSqlDateTime2 method is the correct solution.
Wraith2 commentedon Dec 14, 2020
That's my expectation based on the code as well. The first field access on the row will create the SqlBuffer and then it's used by the subsequent access. the Sql* versions should actually do more work because they're creating an additional object rather than passing back data. This will mean that profiles show most of the time spend in IsDbNull because that's where the value is resolved and it changes the Get* call to a simple lookup, however the overall time shared between them should differ only in the extra time taken to setup callstacks and do duplicated arg checking.
The Sql* types are considered legacy currently as far as I'm aware. They're from .net 1.0 when there were no generics and thus no way to express struct nullability, mostly it was for DataTable as far as I know. Because the types are defined in terms of SQL Server's capabilities other providers have to ignore them, provide their own conversions or provider replacements. It seems unlikely that there will be a new type added to the runtime (dotnet/runtime) at this point but it might be possible to add it directly to sqlclient. I'd rather make the check-null-then-maybe-get pattern faster if it's causing a perf problem in comparison to the Sql type version.
Idealogically I think the separation of null checking and field getting is a purer mapping of the distinction between nulls and values in SQL than a nullable clr type, I consider sql nulls "stronger" than language nulls because of their untyped and uncomparable nature.
bjornbouetsmith commentedon Dec 14, 2020
@Wraith2 I was not aware that the SqlTypes were considered legacy - if that is the case, I would suggest they would be marked as obsolete - and if they are not obsolete, they should really be extended with support for the new data types in SQL Server.
If you can fix the performance issue of IsDbNull - or handle null better in GetXX methods - I am fine by that.
But it seems "strange" that an API was chosen that cannot handle null and requires that caller has to call another method to check for null
the GetSqlXX methods is much easier to use and are more equivalent to what you would expect in my opinion from something that reads from a database.
Imagine SQL server not being able to return NULL from a column and you had to always wrap every column in a ISNULL check before accessing it.
Getting a value back without having to check for null first, will always perform better than having to check for null and then going through almost the same work again just to get the value.
Compare the two methods:
Almost the same work in both methods - both call ReadColumn and both return data from the SqlBuffer - the difference is that the DateTime property throws an exception if the field is null, where the SqlDateTime returns a struct that can tell you if the field was null - similar to a nullable datetime.
A much better API in my opinion
SqlDateTime takes up
Where Datetime takes up:
So almost similar storage requirements in memory.
A solution could be to return nullable types from a range of new methods, since a Nullable should perform similar to the SqlDateTime, since it has:
i.e. a full range of:
GetNullableXX that would simply do the same as the normal methods, but instead of blindly accessing the "Value" field of SqlBuffer it would first call IsNull, i.e.
roji commentedon Dec 14, 2020
I'd recommend not confusing the discussion around DATETIME2 support and SqlClient's SqlTypes with a general discussion on how ADO.NET behaves around nulls - this is simply how the .NET database API works. I wouldn't consider this behavior around nulls a good reason to introduce a GetSqlDateTime2.
The ADO.NET behavior around nulls was a design decision for the entire API (regardless of what we think about it today) - database nulls are generally not represented by .NET nulls, but rather by DBNull (for generic methods this is a problem). There's some relevant discussion on this in dotnet/runtime#26511, even if that's about a proposed generic ExecuteScalar, rather than readere methods.
In any case, as there isn't a performance aspect here, it's trivial to write a simple
GetNullable<T>()extension method yourself, which performs the IsDBNull internally and returns null accordingly.26 remaining items
Wraith2 commentedon Dec 17, 2020
I'm slowly working through merging the two codebases wherever I can and eventually we'll get to the point where the MS team will be needed to make policy decisions about each of the differences. Until then i'd prefer if you add any new code to the shared folder and add it identically in both projects.
Start with just one build and then replicate the changes into the other. This is one of the reasons I offered to help because I'm familiar with the project peculiarities. If you can get the
SqlDataTime2with test for all of it's methods written I can help get it plumbed in.ErikEJ commentedon Dec 17, 2020
It is great that this project is available as open source, but the weight of 20 years of .NET code is present.
bjornbouetsmith commentedon Dec 17, 2020
So I can dump my code into https://github.com/dotnet/SqlClient/tree/master/src/Microsoft.Data.SqlClient/src - and add as
linksinto the two projects?Of course the changes I have to make into existing classes need to go to both places.
ErikEJ commentedon Dec 17, 2020
I think what @Wraith2 is suggesting is that you add the files there, and for example just link from the .NET Framework project, and make tests pass for that, then he will add to .NET Core and add docs links and other quirky stuff.
bjornbouetsmith commentedon Dec 17, 2020
Ok, and how do you feel about me adding
[assembly:InternalsVisibleTo]so I can test SqlBuffer separately with a unit test?Wraith2 commentedon Dec 17, 2020
Not favourably. We've avoided it in the past by including the file directly in the test assembly and writing tests that way. You'll want to add the type tests to the FunctionalTests project because they don't require an active sql connection, anything that does require a database would go in the ManualTests. I've done a shared file to access internal classes in this PR #827
bjornbouetsmith commentedon Dec 17, 2020
@Wraith2 Makes it hard to test my new Property then - since there are two SqlBuffer versions - and they are not the same implementation - so I would need to do conditional includes based on the framework built - that is ugly. But if that is what is needed so I can write a couple of tests for the DateTime2 property, then so be it - but it would be nice if the two versions of SqlBuffer could be merged into one.
Edit: Just tried - and it escalates, then I also have to link SqlCachedBuffer,SqlCahedStream,SqlMetaDataPriv,SqlReource and so forth. It just explodes - and eventually I would probably have to include the entire SqlClient into the test project.
So for now I will not include any tests for SqlBuffer - which is unfortunate but it will implicitly be tested via SqlDataReader so not a huge problem in my opinion - but it would have been easier with
[assembly:InternalsVisibleTo]Wraith2 commentedon Dec 17, 2020
You don't need to test SqlBuffer in the functional tests because it'll be covered in the manual tests through doing real queries. The new type should be the only one you need to add tests for and that file will be shared.
bjornbouetsmith commentedon Dec 17, 2020
Pull request created for your initial comments.
#853
priyankatiwari08 commentedon Sep 17, 2026
/triage
github-actions commentedon Sep 17, 2026
🔍 Triage Summary (on-demand re-triage)
SqlDataReader/SqlBuffertype-conversion gap (GetSqlDateTimevsDATETIME2), closest to general SqlTypes/data-type handling rather than any listed pooling/SNI/AKV/Json/Vector/Async areaSqlDateTimenever supported theDATETIME2range/precision; this is a long-standing design gap, not a regressionAnalysis
SqlDataReader.GetSqlDateTimethrowsInvalidCastExceptionforDATETIME2columns becauseSqlDateTime's range (1753-01-01 through 9999-12-31, ~3.33ms accuracy) cannot represent the fullDATETIME2range (0001-01-01 through 9999-12-31, 100ns accuracy) or values outsideSqlDateTime's bounds.GetDateTimeworks because it maps to the wider CLRDateTimeinstead. This affectsSqlBuffer.get_SqlDateTime()and is a long-open (since 2020) feature/bug with active community interest (5 👍, 51 comments) and a prior attempted fix. Severity: P2 — not a crash-on-open or data-corruption issue, but a real functional gap with a documented workaround-avoidance use case (avoidingIsDBNulloverhead).Next Steps
GetSqlDateTime2/dedicatedSqlDateTime2implementation, and the associated maintainer feedback thread onSqlBuffer/SqlCachedBufferinternals-visibility issues that blocked it, before starting fresh work.SqlDataReader.GetSqlDateTimeshould either (a) throw a clearer, documented exception with guidance to useGetDateTime, or (b) introduce a properly range-checked conversion path (potentially reviving theSqlDateTime2-style approach from Implementation of DateTime2 + accompanying GetSqlDateTime2 method (#846) #853) that handlesDATETIME2values withinSqlDateTime's valid range and cleanly errors otherwise.ref/API surface and manual + functional tests (sync and asyncGetSqlDateTime/GetFieldValueAsyncpaths) are updated per repo conventions.