SQL Server administration and T-SQL development, Web Programming with ASP.NET, HTML5 and Javascript, Windows Phone 8 app development, SAP Smartforms and ABAP Programming, Windows 7, Visual Studio and MS Office software
Development resources, articles, tutorials, code samples, tools and downloads for ASP.Net, SQL Server, Reporting Services, T-SQL, Windows, AWS, SAP HANA and ABAP

Declare and Assign Value to a Variable in SQL Server

SQL Server 2008 introduced sql variable declaration and inline value assignment for T-SQL developers. This new feature enables SQL programmers to create a new sql variable using DECLARE command and directly assign it to a value using "=" (equal) sign in the same statement.

In-line variable declaration and value assignment enables developers to code less and makes it easier to read the SQL code.

Here I'm adding a few in-line variable declaration and value assignment samples for SQL developers. As you see below, instead of coding two lines of SQL statements, now the same task can be fulfilled in a single statement.

declare @sql nvarchar(max) = N''
-- instead of
declare @sql nvarchar(max)
set @sql = N''

Here is another sample SQL variable declare command and value assignment in a single statement.

declare @myGuid uniqueidentifier = NewId()
-- instead of
declare @myGuid uniqueidentifier
set @myGuid = NewId()

One important note for SQL programmers, if you develop applications that will work on different versions of SQL Server, note that in-line variable assignment works with SQL Server 2008 and later versions, not for SQL Server 2005 or SQL Server 2000, etc.

SQL Server

SQL Server 2019 Installation
download SQL Server 2019
download SQL Server 2017
download SQL Server 2016
download SQL Server 2014
download SQL Server 2012
MacOS ve SQL Server 2019

Copyright © 2004 - 2021 Eralper YILMAZ. All rights reserved.