question

atulkrmisra avatar image
atulkrmisra asked

what is the difference in output of following two statements?

what is the difference in output of following two statements? SELECT CAST(GETDATE() AS DATE) AS DATE GO SELECT FORMAT(GETDATE(),'yyyy-MM-dd') AS DATE GO
date-functionsdate-format
1 comment
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

JohnM avatar image JohnM commented ·
Is this homework?
1 Like 1 ·

1 Answer

·
Jeff Moden avatar image
Jeff Moden answered
The "correct" answer is that the first query does no formatting other than what SQL Server thinks it should look like. It only drops the time element because the DATE datatype doesn't have a time element. The output in the GRID mode can sometimes be different than when in the TEXT mode (not in this case, though, and I believe they fixed that problem in 2008).. For a return to other code that consumes the information, it will be perceived as a DATE datatype. The second query formats the date into the format identified by the string literal but that's not the end of it. The FORMAT function is a pig when it comes to performance and is (I measured it) 44 times slower than CONVERT. If it's passed to other consuming code, it will be perceived as character based data and, possibly, cause implicit conversion problems if involved in a JOIN. As a bit of a sidebar, if anyone uses FORMAT for the sake of "portability", remember that nothing is truly portable. True Portability is a myth. To answer the question of "what is the difference in output", you have two pieces of code that work. Run the bloody things and see. If this is on a test or for some homework, then you need to buckle down, try the code, or study what you're instructor has told you to study. If it's for an interview, you probably won't get that particular job and need to buckle down, try the code, and study the SQL Server documentation so you can answer that and similar questions on your next interview. Also, because the word "GO", which is a batch separator, isn't on a separate line, neither will actually produce the expected output. Instead, you'll get the following error. > Msg 102, Level 15, State 1, Line 1 > > Incorrect syntax near 'GO'
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

ThomasRushton avatar image ThomasRushton ♦♦ commented ·
Sorry, @Jeff, the "GO" bits were on a separate line, but the OP failed to mark the text as code, so the line breaks weren't honoured... I've fixed the post...
0 Likes 0 ·
Jeff Moden avatar image Jeff Moden commented ·
Thanks, Thomas.
0 Likes 0 ·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.