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 the architect of SQL Compare versions 4, 5, 6 and 7, SQL Log Rescue and SQL Refactor. He is focused on database internals, database synchronization and database schema evolution.

















<February 2008>
SuMoTuWeThFrSa
272829303112
3456789
10111213141516
17181920212223
2425262728291
2345678
Go With the Flow
 Knowing enough about the routes that messages take is vital to being an effective Exchange admin,... Read more...

When Email Collaboration Could Have Changed History
 In our mission to make history relevant to the busy IT executive, we speculate how Email might have... Read more...

Bunnikins!
 When an IT manager is selected as a victim of office politics of a large corporate, it is time for him... Read more...

Exchange Database Technologies
 One of the most misunderstood technologies in Exchange Server, regardless of its version, is the... Read more...

Top Tips for Exchange Admins
 Michael Francis hands out imaginary Olympic medals to the winner of the August 'Top Tips for Exchange... Read more...