In the recent past, I have been bringing few puzzles around using date and time functions. All these have brought some awesome feedbacks and you all have been sharing some awesome answers. Today’s question comes from an unusual place wherein one of a developer said he was getting unexpected results with working with datetime. So here is how the conversation went:
Dev: Hi Pinal.
Pinal: Yes, buddy. How can I be of help?
Dev: I have a problem working with datetime datatype.
Pinal: Oh is it? Tell me more about it.
Dev: I am trying to CAST a string coming from a front end app to SQL Server.
Pinal: Ok, where is the problem?
Dev: Every now and then, it gives different results than what I try to send via the wire.
Pinal: I am not able to understand. Can you send me an example to understand this better?
Dev: Sure, I will send via email.
After I received the actual code and email, I resumed the conversation.
Dev: Yes, Sir. Did you find the reason?
Pinal: I found the reason and I am going to blog about it tomorrow. It is a simplified version of the query you sent me. So you are about to find the answers there. The hint is: you are doing a convert to smalldatetime
Dev: Well, thanks. I think I will do my homework and try to answer it in your blog too.
This concept was interesting and I planned to share this experience with you folks like a small puzzle. So what are we talking?
Look at the below query and guess what would be the output:
CAST('2015-01-01 12:45:29.755' AS SMALLDATETIME),
CAST('2015-01-01 12:45:35.755' AS SMALLDATETIME)
This is a simple conversion but the two values are different. Why is that? Do you know the reason? Use the comments section to explain this. I may send surprise gift to 2 of the winners.
Reference: Pinal Dave (http://blog.sqlauthority.com)