T-SQL Compound Assignment operators February 21st, 2011

Vinod Kumar

The SQL Server 2008 T-SQL language has been extended to allow compound assignment operators (e.g., addition assignment, subtraction assignment, etc). This can greatly reduce the amount of code and may boost productivity and code readability. Compound assignments may be used with SET, SELECT, and any other place where an assignment is used such as an UPDATE statement.

I personally love to see these getting used, but on a contrary also feel this might make our good old T-SQL champs into a C# programmer for SQL Server. But there is so much of elegance which can be used in this new era of programming.

+=

Add the two values and assign

-=

Subtract the value and assign

*=

Multiply the values and assign

/=

Divide by the value and assign

%=

Modulo and assign

&=

Bitwise AND and assign

^=

Bitwise XOR and assign

|=

Bitwise OR and assign

Some of the typical examples of usage are as below:

DECLARE @var1 VARCHAR(30) = ‘Hello’
SELECT @var1 += ‘ World’
SELECT @var1

UPDATE t1
SET    c1 += 10 

So how many of you use these syntax in your production code? Would love to hear from you.

Share this article

Tags: , , , ,

This entry was posted on Monday, February 21st, 2011 at 13:44 and is filed under Technology. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.


4 Responses to “T-SQL Compound Assignment operators”

  1. Hello!

    We use compound operations a lot in production code, however, we do see a major problem regarding the “slip of the hand”. I try to bring awareness about this simple typo-mistake in my post – http://beyondrelational.com/blogs/nakul/archive/2011/03/03/compound-operators-the-most-common-mistake.aspx

  2. [...] @vinodk_sql posts T-SQL Compound Assignment operators Posted on February 21, 2011 by sqlmashup http://blogs.extremeexperts.com/2011/02/21/t-sql-compound-assignment-operators/ [...]

  3. Jack says:

    Good post.

    Yes I use these in production code.

    Regards,

  4. [...] This post was mentioned on Twitter by Vinod Kumar M (SQL), Srinivasan Anandan. Srinivasan Anandan said: RT @vinodk_sql: T-SQL Compound Assignment operators http://f.ast.ly/VqxNP [...]

Leave a Reply



 

Email
Print