>If you’ve had your hands on T-SQL for quite some time, it wouldn’t be hard for you to identify the new enhancements available in SQL Server 2008. Now just for fun, try to identify what’s unusual in this script, from a SQL Server 2000/2005 point-of-view:
DECLARE
@variable int = 1;
SET @variable += 1;
CREATE TABLE
table1 (col1 int);
INSERT table1
VALUES (@variable),(@variable+1);
If you try to execute this script in SQL Server 2005, you’ll get an error similar to the one below
Msg 139, Level 15, State 1, Line 0
Cannot assign a default value to a local variable.
Msg 137, Level 15, State 2, Line 8
Must declare the scalar variable “@variable”.
Cannot assign a default value to a local variable.
Msg 137, Level 15, State 2, Line 8
Must declare the scalar variable “@variable”.
Now you start thinking, what could be wring with the script? The answer: T-SQL enhancements in SQL Server 2008. First, The DECLARE statement in the first line now has the capability to accommodate initialization of variables unlike before where it only does variable declaration and you need either a SET or SELECT statement to assign values to variables. This is something similar to what you do in .NET, particularly VB.NET (the language enhancement part, in this case) where you can declare and assign values to variables in a single line. You can still use the SET statement to assign values to variables. Next is the += operator (-= is also included). I’ve first encountered this in C++ (Java, C# and VB.NET also have these) where the expression is used to increment (or decrement) variable values. In this case, the value for the variable @variable is set to 2 after the second line because of the += operator. The third item is the existence of multiple row predicates in the VALUES clause. This also works for an UPDATE statement. This means you can now make your INSERT or UPDATE statements shorter with fewer codes. Not that you couldn’t do these in previous versions but this simply means writing less code and getting more work done (although you might be in trouble as your boss might give you more work to do)
Check out my SQL Server 2008 videos at BlogCastRepository.com
Please note: I reserve the right to delete comments that are offensive or off-topic.