Over the years, every time I have worked with Date and time data types, I have learnt something new. There are always tons of tight corners where a number of exceptions happen. Though these are known, for someone who is new, this would take them by surprise and your design decisions can have a larger impact on the output that you are likely to get. These can cause a considerable business impact and compliance if we get stuff wrong. Let us see a puzzle about Date Data Types.
In this puzzle, let me show you some of the default behavior that SQL Server does when working with CAST. Below is an example wherein we take a simple conversion to a DATE.
As you can see, SQL Server went about doing the rounding and it gives the date as 2017-01-13. This seems to be something basic. The puzzle was not around this output.
Task 1
What do you think is the output of the below query? Is it going to be:
SELECT CAST ('2017-1-13 23:59:59.999' AS SMALLDATETIME)
Output:
- 2017-01-13 23:59:00
- 2017-01-13 00:00:00
- 2017-01-14 00:00:00
- Error
What do you think is the answer? Why do you think this is the answer?
Task 2
If you got the Task 1 correct, I think you know a lot about working with datetimes. Having said that, what would be the output for the below:
SELECT CAST('2017-1-13 23:59:59.999999999' AS SMALLDATETIME)
Output:
- 2017-01-13 23:59:00
- 2017-01-13 00:00:00
- 2017-01-14 00:00:00
- Error
Did Task 1 help you? How did you guess it? Why do you think you got this output in task 2?
Reference: Pinal Dave (http://blog.sqlauthority.com)
First appeared on SQL SERVER Puzzle – Conversion with Date Data Types