Variable Assignment in DECLARE Statements

In SQL Server 2012, you can 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 sets its value to 100:

DECLARE @ctr int = 100

Previously, this functionality was possible only 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 ...

Get Microsoft® SQL Server 2012 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.