Saturday, December 05, 2009

SQL Server 2008 T-SQL: DECLARE and SET in the Same Statement

SQL Server 2008 T-SQL DECLARE  SET

In SQL Server 2005, if you wanted to declare a new variable and set its value, you had to write both DELCARE and SET statements:

DECLARE @City VARCHAR(20)

SET @City = 'London'

A new T-SQL improvement in SQL Server 2008 is allows you to write DECLARE and SET in the Same Statement:

DECLARE @City VARCHAR(20) = 'London'

If you try this in SQL Server 2005, you'll get the following error message:

Msg 139, Level 15, State 1, Line 0
Cannot assign a default value to a local variable.

Not a big deal, but can get our code to look better!

Enjoy!

No comments: