0
votes

I'm getting this error when I'm putting outside the loop in side casting working .

Msg 137, Level 15, State 2, Line 2
Must declare the scalar variable "@numCount"

Can you please tell me what I'm doing wrong ??

Thanks

create table #myTemp 
(
     rowid int identity (1,1), 
     Name varchar(200),
     email varchar(200),
     flag bit
)

select * from #myTemp

declare @name varchar(200), @email varchar(200)
declare @numCount int = 20

WHILE (1 <= @numCount)
BEGIN 
    SET @name = 'My Name '+ CAST(@numCount AS VARCHAR)
    SET @email = 'Email'+ CAST(@numCount AS VARCHAR)

    INSERT INTO #myTemp(Name, Email, flag)
    VALUES (@name, @email, 1)

    SET @numCount = @numCount - 1
END
GO

PRINT 'My String' + CAST(@numCount AS VARCHAR) + '***'
3

3 Answers

2
votes

Declaring and setting in the same statement is perfectly valid in SQL Server 2008 R2. The issue is your GO

GO -- < -- starts a new batch and thus the declaration on @NumCount is totally unrealted to this Print.

PRINT 'My String' + CAST(@numCount AS VARCHAR) + '***'
2
votes

It has to do your variable being only accessible in your batch. Get rid of "GO". And it should work.

create table #myTemp (rowid int identity (1,1), Name varchar(200),email varchar(200),flag bit)

select * from #myTemp

declare @name varchar(200),@email varchar(200)
declare @numCount int = 20
while  (1 <= @numCount)
begin 

SET @name =  'My Name '+ CAST(@numCount AS VARCHAR)
SET @email =  'Email'+ CAST(@numCount AS VARCHAR)

INSERT INTO #myTemp
(Name,Email,flag)
values
(@name,@email,1)

SET @numCount = @numCount - 1

END

PRINT 'My String' + CAST(@numCount AS VARCHAR) + '***'
0
votes

You can't declare and initialize a variable at the same time like:

declare @numCount int = 20

Instead do something like:

declare @numCount int;
SET @numCount = 20;