Good question, but unfortunately the explanation is not entirely correct. Especially this part is very misleading:
Also the preceding space is not considered while performing the operation.
Let's look in detail what happens to set @b = ' '+@a + 2
. Since all operators are the same, evaluation order is left to right. So the first partial expression to evaluate is ' '+@a
. This mixes two datatypes: ' ' is varchar(1), and @a is int. Order of precedence dictates conversion of varchar to int, and ' ' is converted to the value 0 (run SELECT CAST(' ' AS int);
if you don't believe me). Since @a is set to 10, the result of this partial expression is 0 + 10, or 10; still types as int.
The next step is to evaluate (' '+@a) + 2
(parentheses added to emphasize evaluation order). We have already seen that (' '+@a)
is equal to the integer value 10, so this is now reduced to 10 + 2
As you have seen, there is no leading space to be considered anywhere. However, even if there was, the words "is not considered" is misleading. I think we would all agree that converting the values '5', ' 5' and ' 5 ' to integer should all result in the value 5 - not because we expect the leading and trailing spaces to be "not considered", but because considering them or not is irrelevant, as they have no impact on the interpretation of the string as a number.
Hugo Kornelis, SQL Server MVP
Visit my SQL Server blog: http://sqlblog.com/blogs/hugo_kornelis