Pages

Thursday, November 10, 2011

Inline Variable Assignment in SQL Server 2008


SQL Server 2008 allows you to declare and initialize a value at the same time, similar to other languages. For some reason, this enhancement was never made to the actual variable declaration.


In previous versions, we could declare a parameter in a stored procedure and assign a default value. However, we could never declare a variable and assign value at the same time. All we could do was declare the variable first and assign it later.


This article illustrates how to declare and assign the values for a variable.


It is a very small change added to SQL Server 2008, it makes a lot of difference when we declare multiple variables.


Example:

---- SQL Server 2005 Way
DECLARE @Var INT
SET @Var = 5
SELECT @Var AS TestVar
GO
---- SQL Server 2008 Way
DECLARE @Var INT = 5
SELECT @Var AS TestVar
GO


No comments: