Does VB.Net DateTime match up to SQL DateTime? - sql-server

I am attempting to use VB.NET EntityFramework to add a new record where on of the fields is of the type of DateTime.
Do the two types of DateTime match up to allow direct saving without any cast or formatting?
I.E Should the following work (where table is WidgetResult and I attempt to add a new record)
Private Sub AddNewWidgetResultRecord ()
Dim newWidgetResult As New WidgetResult()
newWidgetResult.SomeVarChar = "Some widget string"
newWidgetResult.SomeDateTime = DateTime.Now ' Would this line be OK?'
myContext.AddToWidgetResult(newWidgetResult)
myContext.SaveChanges()
End Sub
I have checked a lot of other posts on this but they all seem to concern INSERT queries rather than using the EF provided methods.

Yes, they formats are compatible. BUT, one thing I would be cautious of, if you are trying to compare the SQL Server DateTime (GetDate()) to the VB DateTime.Now. You CANNOT guarantee that those will be equal.

If possible, you want SQL Server to be using datetime2 rather than datetime (but it's only available from 2008 onwards).
datetime itself has a more limited range (only from 1753 onwards, not from the year 0) and precision (milliseconds values are rounded to the nearest value ending with 0, 3 or 7)
datetime2 (SQL Server) and DateTime (.NET) are compatible.
How, precisely, you ensure that the database side is using datetime2 may depend on exactly what form of EF you're using.

The other answers are mostly correct in that the types are compatible, but they are not exactly equivalent.
The biggest difference is what Damien described about how datetime has limited range and precision, while datetime2 has the full range of a DateTime and variable precision.
And Ganders is correct that you can't guarantee DateTime.Now == getdate(). Mostly this is because of the clock ticking away in between your calls, but also it's possible that DateTime.Now is called from a web server and getdate() is called from a SQL Server and they are on two different computers. Their clocks might not be perfectly synchronized, or they might have different time zone settings.
But the other point that has not been discussed is that DateTime has its very important .Kind property, which is one of three DateTimeKind values. Either Utc, Local, or Unspecified. A SQL Server datetime or datetime2 does not have this concept.
So if you have a Utc or Local kind of DateTime, when you save and then retrieve it, you will find that it is now Unspecified. In other words - the kind does not survive the round-trip.
By comparison, the related .NET DateTimeOffset type will fully round-trip with a SQL Server datetimeoffset type.
You can read more about this (and other concerns) in my blog post The Case Against DateTime.Now.

Related

SQL Server: Using date in ISO 8601 format in WHERE clause

In SQL Server 2014 I tried the following query:
select *
from MyTable
where StartDate = '2021-12-31T00:00:00.0000000'
I get this error:
Msg 295, level 16, state 3, row 3
Conversion failed when converting character string to smalldatetime data type.
As far as I can tell this string is in ISO 8601 format, so it should be accepted by SQL Server (I read that this should actually be the preferred format when passing dates to SQL Server).
Is there a way to tell SQL Server to accept this format?
Please note: this query is actually generated by Linq in an Entity Framework Core DataContext, so I can't change the query itself in any way.
Older versions of EF Core did not support smalldatetime.
This was fixed in version 2.2.0 in 2018.
Update your EF Core version to something more recent than 2.2.0.
If you are using a modern EF Core version, then you should file this as a regression bug.
But better yet: don't use smalldatetime in your database design in the first place. Use datetime2(n) or some other appropriate type instead.
There is no good reason for using smalldatetime in a new database design (nor other types like text, ntext, image, timestamp, etc)
And you should be able to run ALTER TABLE to change the column type to datetime2(7) with no compatibility issues unless something else is really horribly designed in your system, in which case you should fix that.
If you really need to expose data as smalldatetime because of some horrible and opaque, but business-critical, binary that you can't rebuild then you can add a VIEW, SYNONYM and other shims to transparently convert datetime2(n) to smalldatetime while the rest of the system can live in modernity.

Date format changed on imported SQL Server DB

I have migrated a SQL Server database from one server to another. I did this via export to BAK and then Restore on the new machine.
Seems to be a different format somewhere, as a simple query that was working previously, is now throwing an error, but I cannot see what it might be (collation and 'containment' info seem the same).
The old SQL Server version: Microsoft SQL Server 2012 - 11.0.6598.0 Express Edition
The new SQL Server version: Microsoft SQL Server 2019 - 15.0.2080.9 Express Edition
The error, below, refers to a date format:
SELECT userID FROM tblLogin
WHERE CAST('30/09/2021 00:52:14' AS datetime) < DATEADD(n,600,accessDate)
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
(Column accessDate is of type datetime, null)
Always always ALWAYS use the ISO-8601 date formats for literals in Sql Server. For historical reasons, the preferred option for date-only values is different than date-time values, so you want either yyyy-MM-ddTHH:mm:ss for date and time or yyyyMMdd for date-only. But the really important thing is always go in order from most significant (year) to least significant (second).
Anything else isn't really a date literal at all: it's a string you must convert to a date.
If we follow this correct convention (because anything else really is incorrect), you get it down to this (which doesn't even need the CAST() anymore, because Sql Server can interpret it as datetime from the beginning):
SELECT userID
FROM tblLogin
WHERE accessDate > DATEADD(n, -600, '2021-09-30T00:52:14')
Also note I inverted the check, moving the DATEADD() function to act on the literal, instead of the column. This is always preferred, because it can work with any index you may have on the accessDate column. The original code would have rendered any such index worthless for this query.

MS Access Date() syntax in query to SQL Server

I have found several posts on using the GETDATE() function for SQL Server linked table while in an Access front-end VBA procedure. Those posts are focused on the WHERE clause of the query, but I have been unable to find corresponding information on use of GETDATE() for column assignment.
For example, I understand that in the WHERE clause, I would use something like this:
WHERE MyDate = CAST(GETDATE() AS DATE)
However, I am getting syntax errors in VBA when I try to assign the current date to a column, like this:
INSERT INTO MyTable ( SomeValue, TheDate ) SELECT 'Widget' AS Expr1, CAST(GETDATE() AS DATE) AS Expr2;
In this example, TheDate is defined as DateTime in SQL Server. Written like this, VBA reports "Syntax error (missing operator) in query expression 'CAST(GETDATE() AS DATE)'. I tried to surround the expression with Access-friendly # date delimiters, but no luck there.
After spending about 30 minutes searching stackexchange.com various ways for MS Access Date() in SQL, I have been unable to find this. However it is so simple I am sure it was already answered somewhere.
In MS Access you likely (not 100% sure for linked SQL, you have to experiment) should use Now() and Date() functions. First one is equivalent to getdate() in SQL, the second one returns current date without time.
If you run this in Access on a linked table (not a PT query), it should read:
INSERT INTO MyTable ( SomeValue, TheDate )
VALUES ('Widget', Date());
There seems to be some confusing here. If you building a Access query, then ZERO ZERO of the SQL server date functions and syntax matter. Your SQL MUST continue to be written to Access standards unless you using a pass-though query.
However, I seen this 100x times here.
What is the data type on sql server side?
Is it datetime, or datetime2?
And double, triple, qudadropes, (and more) check the linked table in desing mode.
If you link to SQL server using the standard legacy "SQL Server" driver. The one that been shipped for 20 years since windows 98SE?
You MUST check if Access is seeing those columns as text, or as date columns (which in Access always allow a time part if you want).
Access code, queries, forms and EVERYTHING should require ZERO changes if you migrate that data from Access to SQL server and link the table. Again: ZERO ZERO changes.
However, if you used datetime2 on the SQL server side? Then you CAN NOT use the legacy "SQL server driver" when linking table. The reason is they don't support the newer datetime2 format. As a result, Access will actually see, use, and process that column as a text column. You REALLY, but REALLY do not want that to occur.
Why?
Becuase then you spend the next week asking questions on SO about how some date code or column or query does not work.
again:
ZERO ZERO changes are required in Access. If your dates are starting to break, then the issue is not date formats, but that column is now being seen by access as a TEXT data type.
Soltuion:
Either change the sql side datetime2 columns to datetime, and re-link.
or
re-link your tables using a newer native 11 (or later - up to 18 now). that way, access will see/use/process the datetime2 as a correct date format in Access.
So, before you do anything? Open one of the Access tables linked to SQL server in design mode. (ignore the read only prmompt). Now, look at the data type assigned to the date columns. If they are text, then you have a royal mess.
You need to re-link using the newer ODBC drivers.
Zero of your existing code, sql and quires should be touched or even changed if you using a linked table to sql server. But then again, if you linked using the wrong SQL ODBC driver, then Access cannot see nor process those datetime2 columns as date - it will be using text, and you beyond really don't want to allow that to occur.
In summary:
Any date code, SQL updates, sorting, query, VBA code, form code, reports should continue to work with ZERO changes. If you are making changes to dates after a migration, then you done this all wrong, and those date columns are not being seen by access as date columns.
Either get rid of all datetime2 columns and then re-link (change them server side to datetime). Or re-link the tables using a native 11 or later ODBC driver. Either of these choices will fix this issue.
This is a fix that requires ZERO code, and zero changes to Access dealing with dates.

storing datetime2 in ssis variable

I'm using SQL Server 2012 Enterprise. I have a requirement where I've to store data with DATETIME2 datatype in SSIS Variable. Unfortunately, SSIS variables don't have that data type.
If I'm storing it into datetime data type, I'm losing information. Can anyone help in giving workaround?
PS: My source system is SQL Server 2012 as well and I'm reading the data from column with datetime2 datatype.
SSIS, at least currently, has a "known" shortfall in that the variable value type, DateTime only has a precision to the second; effectively the same as a datetime2(0). If you therefore need to store anything more accurate that a second, such as if you are using datetime and the 1/300 of a second is important or if you are using datetime2 with a precision of 1 or more, the value type DateTime, will not serve your goal.
A couple of different options are therefore to store the value of as a String or numerical value. This does, however, come with it's own problems; most and foremost that neither of these datatypes are date and time datatypes.
It therefore depends what your goal is. I would most likely make use of a String datatype and ensure it has the ISO format ('yyyy-MM-ddThh:mm:ss.nnnnnnn'). If you're then using something like a T-SQL Task you can pass your variable as normal to the task and the data engine will interpret the literal string as a datetime2(7) (or whichever literal precision you used).

Why does Azure lose timezone information in DateTimeOffset fields?

We're working on a IOS app using Microsoft's Azure Mobile Services. The web GUI creates date-time as DateTimeOffset fields, which is fine. But when we have the mobile put datetimes into the database, then read them from the database, via Entity Framework, we're seeing them adjusted to UCT. (We see the same thing when we view the records in SSMS.)
I've always been frustrated by the lack of timezone support, in SQL's standard datetime types, and I'd thought that DateTimeOffset would be better. But if I wanted my times in UTC, I'd have stored them in UTC. If a user enters a time as 3:00 AM, CST, I want to know he entered CST. It makes as little sense to me to convert it to UTC, and throw away the offset, as it did to assume that 3:00 AM CST and 3:00 AM PDT were the same.
Is there some kind of database configuration I can do to keep the Azure database from storing the dates in UTC?
The issue is that at some point in Azure Mobile Services, the property is converted to a JavaScript Date object, which cannot not retain the offset.
There are a couple of blog posts describing this issue, and possible workarounds:
https://blogs.msdn.microsoft.com/carlosfigueira/2013/05/13/preserving-date-time-offsets-in-azure-mobile-services/
http://michele-colombo.it/2014/11/azure-mobileservices-how-to-properly-save-datetimeoffset-with-offset/
Essentially, they both take the same approach of splitting out the offset into a separate field. However, looking closely at these, they both make a crucial mistake:
dto.DateTime.ToUniversalTime()
Should actually be:
dto.UtcDateTime
The DateTime of a DateTimeOffset will always have DateTimeKind.Unspecified, and thus ToUniversalTime will assume the source is local, rather than using the offset of the DTO.
There are a few other similar errors I see in the code in these posts, so be careful to test thoroughly. However, the general approach is sound.
We're using a Node.js backend and noticed the same thing with DATETIMEOFFSETs read from our SQL Server database being returned in UTC regardless of the offset. Another alternative is to convert the DATETIMEOFFSET at the query-level so that it is outputted as a string with the timezone information. The following converts a DATETIMEOFFSET(0) field to the ISO8601 format; however, other possible styles can be used as documented here:
SELECT CONVERT(VARCHAR(33), [StartDate], 126) AS [StartDate] FROM [Products];
The new output is now: "2016-05-26T00:00:00-06:00" instead of "2016-05-26T06:00:00+00:00"
Of course, this means that the client must serialize the string into their respective format. In iOS, the ISO8601 library can be used to read the output as either a NSDateComponents or NSDate.
One benefit of this approach is that any database-level checks or triggers can do date comparisons using the DATETIMEOFFSET instead of trying to take into account a separate offset column with a basic DATETIME.

Resources