Wednesday, April 16, 2008

SQL Server 2008: in-line declaration and assigning values to variable

It might sound strange, but with SQL 2008, I would say much awaited feature of assigning default value to a variable at the time of declarion has been introduced.
It means you can assign a default value to the declared variable in-line without adding extra SET statement in the new line.

Syntax: DECLARE @local_variable [AS] data_type [ = value ]
Here [= value] is optional and is used to assign a value to the variable in-line. The value can be a constant or an expression, but it should match the variable declaration type or be implicitly convertible to that type.

Example:
DECLARE @v1 int;
/* Also allowed:
DECLARE @v1 int = 10;
*/
SET @v1 = 10;
SELECT @v1;

No comments: