Variable Assignment in DECLARE Statement

In SQL Server 2008, you can now set a variable’s initial value at the same time you declare it. For example, the following line of code declares a variable named @ctr of type int and set its value to 100:

DECLARE @ctr int = 100

Previously, this functionality was only possible with stored procedure parameters. Assigning an initial value to a variable required a separate SET or SELECT statement. This new syntax simply streamlines the process of assigning an initial value to a variable. The value specified can be a constant or a constant expression, as in the following:

DECLARE @start_time datetime = getdate()

You can even assign the initial value via a subquery, as long as the subquery returns only a single ...

Get Microsoft® SQL Server 2008 R2 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.