What is the general guidance on when you should use CAST
versus CONVERT
? Is there any performance issues related to choosing one versus the other? Is one closer to ANSI-SQL?
This question is related to
sql
sql-server
database
tsql
You should also not use CAST
for getting the text of a hash algorithm. CAST(HASHBYTES('...') AS VARCHAR(32))
is not the same as CONVERT(VARCHAR(32), HASHBYTES('...'), 2)
. Without the last parameter, the result would be the same, but not a readable text. As far as I know, You cannot specify that last parameter in CAST
.
CAST is standard SQL, but CONVERT is only for the dialect T-SQL. We have a small advantage for convert in the case of datetime.
With CAST, you indicate the expression and the target type; with CONVERT, there’s a third argument representing the style for the conversion, which is supported for some conversions, like between character strings and date and time values. For example, CONVERT(DATE, '1/2/2012', 101) converts the literal character string to DATE using style 101 representing the United States standard.
Convert has a style parameter for date to string conversions.
To expand on the above answercopied by Shakti, I have actually been able to measure a performance difference between the two functions.
I was testing performance of variations of the solution to this question and found that the standard deviation and maximum runtimes were larger when using CAST
.
*Times in milliseconds, rounded to nearest 1/300th of a second as per the precision of the DateTime
type
Something no one seems to have noted yet is readability. Having…
CONVERT(SomeType,
SomeReallyLongExpression
+ ThatMayEvenSpan
+ MultipleLines
)
…may be easier to understand than…
CAST(SomeReallyLongExpression
+ ThatMayEvenSpan
+ MultipleLines
AS SomeType
)
CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates
Source: Stackoverflow.com