• da-zero (10/29/2010)


    edit: your explanation comfirms my initial statement that the explanation of the questions' poster is incorrect, as it has nothing to do with pre-increment operators, but with misplacing the + so that SQL Server ignores the unary operator. Maybe the question would have been more difficult (or tricky) if it contained =-

    Agreed; the explanation is lacking.

    Pre-increment operators in C++ are a double + (or a double -) before the operand. Like "a = ++b" - this adds 1 to b, then assigns the result to a. You can also use post-increment: "a = b++" first assigns the value of b to a, then adds one to the value of b. And if you use -- instead of ++, you get pre- and post-decrement.

    SQL Server understands neither of these. The post-increment syntax should result in a syntax error. The pre-increment syntax runs, but is interpreted as a sequence of two unary plus operators (so "SET @a = ++@b;" is interpreted as "SET @a = +(+(@b));"). With decrement, the results are reversed - post-decrement runs (because "SET @a = @b--;" is interpreted as "SET @a = @b-2", since -- is the start of an inline comment). The pre-decrement does not run (also becuase -- is a comment token).

    Based on the supplied answer options and the explanation, I think the question author tried to confuse us with the syntax for compound operators, that was introduced in SQL Server 2008. "SET @a += @b-2;" (note that the order of = and + is not the same as in the QotD!) will generate an error message in SQL Server 2005 and older; in SQL Server 2008 and later, it will add the value of @b-2 to @a, i.e., it is equivalent to "SET @a = @a + @b-2;". One of the answers provided matches exactly what would be returned if the query had used += instead of =+.


    Hugo Kornelis, SQL Server/Data Platform MVP (2006-2016)
    Visit my SQL Server blog: https://sqlserverfast.com/blog/
    SQL Server Execution Plan Reference: https://sqlserverfast.com/epr/