SQL SERVER 2008 – 2011 – Declare and Assign Variable in Single Statement
Posted
by pinaldave
on SQL Authority
See other posts from SQL Authority
or by pinaldave
Published on Fri, 18 Mar 2011 01:30:23 +0000
Indexed on
2011/03/18
8:13 UTC
Read the original article
Hit count: 377
Pinal Dave
|PostADay
|sql
|SQL Authority
|SQL Query
|SQL Scripts
|SQL Server
|SQL Tips and Tricks
|T SQL
|Technology
Many of us are tend to overlook simple things even if we are capable of doing complex work. In SQL Server 2008, inline variable assignment is available. This feature exists from last 3 years, but I hardly see its utilization. One of the common arguments was that as the project migrated from the earlier version, the feature disappears. I totally accept this argument and acknowledge it. However, my point is that this new feature should be used in all the new coding – what is your opinion?
The code which we used in SQL Server 2005 and the earlier version is as follows:
DECLARE @iVariable INT, @vVariable VARCHAR(100), @dDateTime DATETIME
SET @iVariable = 1
SET @vVariable = 'myvar'
SET @dDateTime = GETDATE()
SELECT @iVariable iVar, @vVariable vVar, @dDateTime dDT
GO
The same should be re-written as following:
DECLARE @iVariable INT = 1, @vVariable VARCHAR(100) = 'myvar', @dDateTime DATETIME = GETDATE()
SELECT @iVariable iVar, @vVariable vVar, @dDateTime dDT
GO
I have started to use this new method to assign variables as I personally find it very easy to read as well write.
Do you still use the earlier method to declare and assign variables? If yes, is there any particular reason or just an old routine? I am interested to hear about this.
Reference: Pinal Dave (http://blog.SQLAuthority.com)
Filed under: Pinal Dave, PostADay, SQL, SQL Authority, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology
© SQL Authority or respective owner