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
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.