Click here to monitor SSC

Andras

Software Architect - Red Gate Software

Can I redeclare a variable in T-SQL? Teaser for SQL Bits

Published Friday, February 15, 2008 1:17 PM

Variables in T-SQL behave differently from what people may be used to in languages like C or C#. The scope of a variable is the batch in which it is declared. This may not be intuitive to people who are used to local variables. So let’s look at an interesting example:

 

DECLARE @counter INT

SET @counter = 0

 

WHILE @counter < 100

    BEGIN

        DECLARE @value INT

        SET @value = ISNULL(@value, 0) + 5

        SET @counter = @counter + 1

    END

 

SELECT  @value

 

 

In this example we have a simple loop. The loop counter is a variable @counter. What is interesting that inside the loop we have a variable declaraion for @variable. We assign it a value (if it was null we set it to 5, if it was not null, we increment it by 5). Does this make sense? How could I ever consider the previous value if I’ve just declared the variable? What is unusual for many developers, is that the declaration is evaluated only once. This means that in the second iteration of the loop the @value variable is already declared and set, so we are incrementing it by five in every subsequent iteration.

At the end of the loop we can access the @value variable (do not forget that the scope is the whole batch), and the value will be 500 (100 iterations, 100 times adding 5).

Variable declarations are evaluated at the time of parsing, and the scope is the whole batch. Because of this, you cannot have two declare statements for the same variable in a batch, even if the only one declaration is reachable in the code. For example, the following statement will result in a parsing error:

IF 1 = 1

    DECLARE @a INT

ELSE

    DECLARE @a INT

 

The error is:

Msg 134, Level 15, State 1, Line 4

The variable name '@a' has already been declared. Variable names must be unique within a query batch or stored procedure.

 

 

If you would like to know more about how transient data, like the above variable, is handled in SQL Server, come to my session at SQL Bits in Birmingham (UK) on 1 March, 2008. Like the previous SQL Bits event it is free. The last one was held in Reading half a year ago, and with 20 sessions and over 300 people attending it, it provides a unique opportunity to learn about SQL Server, as well as to meet your fellow DBAs and SQL developers in the UK. I will talk about transient data in SQL Server, and you can learn about what is stored in tempdb, how the tempdb can be a performance bottleneck, what the differences between temporary tables and table variables are, what is stored in the transaction log file and how its can size be kept under control.

by András

Comments

 

puzsol said:

My favourite gotcha with scoping and batches is this...

declare @id
insert into identity_table
values (val1, val2)
set @id = SCOPE_IDENTITY()
....
go
...
select * from identity_table where id = @id

you get the error: "Must declare the scalar variable "@id"."
Why?  They are in the same file, I declared it just there!  Of course it's because the go statement separates the file into two batches... meaning for large set-up scripts you either don't use go statements or you find another way to retrieve the row you were after.
February 16, 2008 12:03 AM
 

Martin Smith said:

Random SQL Variable fact. The following is perfectly valid

declare @ int
set @ = 5
February 27, 2008 2:43 PM
You need to sign in to comment on this blog

About András

András Belokosztolszki is a software architect at Red Gate Software Ltd. He is a frequent speaker at many UK user groups and events (VBUG, NxtGen, Developer’s Group, SQLBits). He is primarily interested in database internals and database change management. At Red Gate he has designed and led the development of many database tools that compare database schemata and enable source control for databases (SQL Compare versions 4 to 7), refactor databases (SQL Refactor) and show the history of databases by analyzing the transaction log (SQL Log Rescue). András has a PhD from Cambridge and an MSc and BSc from ELTE, Hungary. He is also a MCSD and MCPD Enterprise. See his articles on simple-talk.
<February 2008>
SuMoTuWeThFrSa
272829303112
3456789
10111213141516
17181920212223
2425262728291
2345678
How to Kill a Company in One Step or Save it in Three
 The majority of companies that suffer a major data loss subsequently go out of business. Wesley David... Read more...

Migrating from OCS 2007 R2 to Lync: Part 4
 Having migrated the rest of our users and legacy resources across and started getting ready to... Read more...

Automated Script-generation with Powershell and SMO
 In the first of a series of articles on automating the process of building, modifying and copying SQL... Read more...

Seth Godin: Big in the IT Business
 Seth Godin has transformed our understanding of marketing in IT. He invented the concept of 'permission... Read more...

Using SQL Test Database Unit Testing with TeamCity Continuous Integration
 With database applications, the process of test and integration can be frustratingly slow because so... Read more...