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 Kodyaz SQL Server and T-SQL Development Tutorials
Development resources, articles, tutorials, samples, codes and tools for .Net, SQL Server, Windows, Windows Phone, SAP and ABAP, like SAP UI5, Screen Personas, etc.




download SQL Server 2016
download SQL Server 2014
download SQL Server 2012



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.







Related SQL Resources

SQL Server Articles

SQL Server 2012

SQL Server Tools

SQL Blog

SQL Server 2008 Blog

Certification Exams Blog

Reporting Services Blog

Analysis Services Blog

MS SQL Server Forums







Copyright © 2004 - 2017 Eralper YILMAZ. All rights reserved.
Community Server by Telligent Systems