I'm having a global Variable, which get increment in the Nested While Loop. In Each Iteration it Resets the Value to 1 (i.e., Initially Initialized Value).
Sample Re-produce able Code:
SET NOCOUNT ON;
DECLARE @GlobalCounter INT = 1;
DECLARE @CounterOne INT = 1;
DECLARE @CounterTwo INT = 1;
WHILE(@CounterOne <= 10)
BEGIN
PRINT 'Outer Loop:';
PRINT @GlobalCounter;
DECLARE @SerialInfo table
(
[Id] [int] IDENTITY(1,1) NOT NULL,
[SNumber] [NVARCHAR](20) NOT NULL,
PRIMARY KEY ([Id])
);
SET @CounterTwo = 1;
WHILE(@CounterTwo <= 10)
BEGIN
DECLARE @SerialNumber NVARCHAR(20);
SET @SerialNumber = 'SRL: ' + CONVERT(NVARCHAR(10), @GlobalCounter);
INSERT INTO @SerialInfo([SNumber]) VALUES (@SerialNumber);
SET @GlobalCounter = @GlobalCounter + 1;
SET @CounterTwo = @CounterTwo + 1;
END
SET @CounterTwo = 1;
WHILE(@CounterTwo <= 10)
BEGIN
SET @SerialNumber = '';
SELECT @SerialNumber = [SNumber] FROM @SerialInfo WHERE [Id] = @CounterTwo;
PRINT @SerialNumber;
SET @CounterTwo = @CounterTwo + 1;
END
SET @CounterOne = @CounterOne + 1;
END
Kindly assist me in terms of Global Variable Scope and its value. How to achieve the Expected Results
SRL: 1
SRL: 2
SRL: 3
.
.
.
SRL: 99
SRL: 100
select * from @SerialInfoafter the loop you should see the problem. There's probably a better way to do this entire job without loops or table variables, if you could describe the overall objective, which I assume this is part of a proposed solution.