1

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

migrated from serverfault.com Aug 21 '18 at 17:28

This question came from our site for system and network administrators.

2

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

  • Thanks Greg. Now I can go back and respond that an error in entry would result in another date being displayed but that it would be a valid date and that a test on whether a date is valid or not is redundant. Thanks! – Matt Bartlett Aug 13 '18 at 10:11
2

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.

0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.