BackToBasics: CAST vs. CONVERT
There are several T-SQL language features where you have a choice of two or more approaches. I've talked before about old-style vs. explicit inner joins, how to express the "not equal to" operator, and whether you should use the newer FORMAT function.
Another area where I see a lot of inconsistency is the simple choice between CAST
and CONVERT
.
In many cases, there is no material difference. For example, it is true that these do the same thing:
Neither is really any more typing than the other, and they both work the exact same way under the covers. So it would seem that the choice between CAST
and CONVERT
is merely a subjective style preference. If that were always true, however, you probably wouldn't be reading this post.
There are other cases where you need to use CONVERT
in order to output correct data or perform the right comparison. Some examples:
Interpreting a date from a string
It is very common to accept freeform date strings as input, and then translate those to date
or datetime
within SQL Server. This is very easy to do with CONVERT
- let's say people are passing in m/d/y
strings, you can get the right date by using CONVERT
with style 101: