31

I've come across a interesting scenario (at least for me) in a stored procedure. Would like to have experts opinion and thoughts on it.

DECLARE @loopcounter INT
SET @loopcounter=10

WHILE @loopcounter > 0
BEGIN
  DECLARE @insidevalue int

  IF (@loopcounter%2 = 0)
  SET @insidevalue = @loopcounter

  PRINT 'Value_' + CAST(@insidevalue AS NVARCHAR) + '_'

  SET @loopcounter = @loopcounter - 1
END

I was expecting this block will give the output as below

Value_10_

Value_ _

Value_8_

Value_ _

Value_6_

Value_ _

Value_4_

Value_ _

Value_2_

Value_ _

Instead I got output as below:

Value_10_

Value_10_

Value_8_

Value_8_

Value_6_

Value_6_

Value_4_

Value_4_

Value_2_

Value_2_

I thought if I declare a variable inside a while block, then for every iteration it will reset the value to NULL or default value (from c# background).

If this is by design then my question is how does SQLServer treat 'DECLARE' statement for that variable inside while block? Does it ignore it as the variable is already in memory?

Can somebody please explain me this behavior?

8 Answers 8

39

The variable scope is the whole batch in this case a stored procedure.

It isn't re-declared every loop

So this is exactly as expected

Edit:

There is a recent blog article which is quite similar. The author was quickly corrected :-)

4
  • 1
    You mean it ignores declare statement in the next iteration?
    – JPReddy
    May 18, 2011 at 14:06
  • 4
    If you want to put it like that, yes. But it isn't ignored because it has no meaning. SQL doesn't have scope like you are expecting.
    – gbn
    May 18, 2011 at 14:08
  • 14
    I make a habit out of manually resetting variables that I declare within T-SQL loops in order to prevent this sort of behavior. It is indeed strange if you're used to working in a language like C#. May 18, 2011 at 14:10
  • @John: Even I'll make this habit from now onwards, I never cared about it earlier.
    – JPReddy
    May 18, 2011 at 14:23
18

From Transact-SQL Variables

The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.

The DECLARE is not in itself an executable statement. The variable declarations are all identified at compile time and the memory reserved for them in the execution context.

If you use the 2008+ Declare and Set syntax. The Set part of the statement will occur every loop iteration however.

DECLARE @loopcounter INT
SET @loopcounter=10

WHILE @loopcounter > 0
BEGIN
  DECLARE @insidevalue INT = NULL

  IF (@loopcounter%2 = 0)
  SET @insidevalue = @loopcounter

  PRINT 'Value_' + CAST(@insidevalue AS NVARCHAR) + '_'

  SET @loopcounter = @loopcounter - 1
END
1
  • Is that mean @insidevalue will be NULL for every start of the loop (ie. re-initialized to NULL)?
    – Sam
    Sep 18, 2021 at 9:38
14

Try this for fun

if 1 = 0
begin
  -- will never happen
  declare @xx int
end  
else  
begin
  set @xx = 1
end  
print @xx

Apparently the declare code does not have to be executed. Only be declared before it is used.

This don't work

if 1 = 0
begin
  -- will never happen
  set @xx = 1
end  
else  
begin
  declare @xx int
end  
print @xx
1
  • 2
    +1 Interesting, if its not 'executed' it also won't pick up an initialiser e.g. declare @xx int = 999
    – Alex K.
    May 18, 2011 at 14:19
6

From Declare:

The scope of a local variable is the batch in which it is declared.

There are no more "local" scoping rules in T-SQL. It also means that you can't declare the same variable name inside IF and ELSE blocks.

All Declare does is declare a variable. It has no relation to assignment. The value of any variable that has never been assigned to is NULL. But thereafter, the only way the variables value will become NULL again is through an explicit assignment.

If you need it to be NULL at the top of each loop iteration, therefore, you must explicitly assign it.

3

In T-SQL a WHILE..END is not individually scoped, you can for example SELECT @insidevalue after the WHILE's END.

1
 DECLARE @loopcounter INT
 DECLARE @insidevalue int
   SET @loopcounter=10
       WHILE @loopcounter > 0
        BEGIN
          IF (@loopcounter%2 = 0)
          BEGIN
          SET @insidevalue = @loopcounter
          PRINT 'Value_' + CAST(@insidevalue AS NVARCHAR) + '_'
          END
    ELSE
      PRINT 'Value_'+' '+'_'
      SET @loopcounter = @loopcounter - 1
   END
0
DECLARE @loopcounter INT
SET @loopcounter=10

WHILE @loopcounter > 0
BEGIN
  DECLARE @insidevalue int
  IF (@loopcounter%2 = 0)
  begin

    set @insidevalue=@loopcounter
    PRINT 'Value_' + CAST(@insidevalue AS NVARCHAR) + '_'
  end
  ELSE

    PRINT 'Value_' + ' ' + '_'
    SET @loopcounter = @loopcounter - 1
END
2
  • 1
    It will be more understandable and looking goood if you can give a bit of description and do the code formatting evenly
    – RinoTom
    Sep 20, 2013 at 7:28
  • This is just a copy from another answer with 0 explaination
    – jasttim
    Apr 24, 2019 at 11:39
0

Integer data types often don't have NULL's only 0's

Declare statement won't happen each time within the loop

why don't you just use

DECLARE @loopcounter INT
SET @loopcounter=10
WHILE @loopcounter > 0
BEGIN
  IF @loopcounter%2 = 0
  PRINT 'Value_' + CAST(@loopcounter AS NVARCHAR) + '_'
  else
  PRINT 'Value_ _'
  SET @loopcounter = @loopcounter - 1
END

That gives:

Value_10_
Value_ _
Value_8_
Value_ _
Value_6_
Value_ _
Value_4_
Value_ _
Value_2_
Value_ _

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.