Published on

July 15, 2015

Understanding DateTime Conversion in SQL Server

In today’s blog post, we will discuss an interesting concept related to datetime conversion in SQL Server. This topic was inspired by a conversation I had with a developer who was experiencing unexpected results when working with datetime data type.

The developer approached me with a problem he was facing while trying to CAST a string from a front-end application to SQL Server. He mentioned that occasionally, the converted values were different from what he expected. Intrigued by this issue, I asked him to provide me with an example to better understand the problem.

After receiving the code and email, I analyzed the situation and discovered the reason behind the unexpected results. I decided to share this experience with you all as a small puzzle. So, let’s dive into it!

Consider the following query:

SELECT CAST('2015-01-01 12:45:29.755' AS SMALLDATETIME), CAST('2015-01-01 12:45:35.755' AS SMALLDATETIME)

On first glance, it seems like a simple conversion. However, the two values being converted are different. Can you guess why?

The reason behind this discrepancy lies in the precision of the SMALLDATETIME data type. In SQL Server, the SMALLDATETIME data type has a precision of one minute. This means that any seconds or milliseconds beyond the minute will be rounded off.

In the given example, the first value ‘2015-01-01 12:45:29.755’ will be rounded down to ‘2015-01-01 12:45:00’, while the second value ‘2015-01-01 12:45:35.755’ will be rounded up to ‘2015-01-01 12:46:00’.

This behavior of the SMALLDATETIME data type can sometimes lead to unexpected results, especially when dealing with precise time calculations. It is important to be aware of this limitation and choose the appropriate data type based on your requirements.

I hope this puzzle helped you understand the concept of datetime conversion in SQL Server. If you have any further questions or insights, feel free to share them in the comments section below. As a token of appreciation, I will be sending surprise gifts to two lucky winners who provide the correct explanation.

Stay tuned for more interesting SQL Server concepts and puzzles!

Reference: Pinal Dave (https://blog.sqlauthority.com)

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.