Question

I have been asked to write a series of tests within SQL. Many of them are to test if a certain DateTime columns held in the system is a valid date.

Given that the all the fields in question are Datetime column and any changes made to them by end-users are through a GUI front end that already has date validation tests, not to mention that the SQL connector would through up an error if an invalid was passed through anyway.

My question is that under what circumstances could a DateTime column end up holding an invalid date, i.e 20/40/2018.

We are running SQL Server 2008

Kind regards

Matt

Was it helpful?

Solution

SQL Server will not allow an invalid date. Internally, the date part of a DateTime column is just a number/four bytes that represents dates between January 1, 1753, through December 31, 9999. SQL Server does not know anything about and will not use invalid dates. An attempt to save an invalid date will result in an error.

If you want to confirm this, write some code that attempts to store all possible number combinations for the digit groups in a column.

It is possible, however, to inadvertently store the wrong date, due to SQL Server DateTime supports multiple formats, however that should be handled by your business logic layer. For example, someone may enter 07/06/2018, intending the date to be June 7. In most cases this can be avoided by using ISO 8601 DateTime format when a DateTime needs to be represented as a string.

https://en.wikipedia.org/wiki/ISO_8601

OTHER TIPS

Although, as the other answers have identified, SQL Server will not allow you to store invalid date data in a datetime column, perhaps the bigger question is what makes a date valid in the context of your specific application.

For example, if you're dealing with birth dates for living people, then it's unlikely that you'll want to accept a date of 1756-04-08, since that would indicate a person is 262 years old. Perhaps you need to build a set of tests that ensure the front-end is only able to insert data that meets the criteria for your business rules.

Under only one circumstance: that sql server has a bug. All the other tests are irrelevant - it always runs down to SQL having a bug.

Well, the other one would be someone is not smart enough to store it as DateTime, but you ruled that out.

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top