I was writing bunch of operations in sql, was using SQL
Server 2008 R2. I declared one INT variable and was trying to use inside select
statement, I was getting error as "Must declare the scalar variable
"@numberOfCards"."
SQL scripts looks like something similar to this: -
declare
@numberOfCards int;
set
@numberOfCards = 3; --some number
;
;
;
GO
select
* from CardsRepository where CardsCount = @numberOfCards
Reason of issue:
Culprit was GO statement. The GO command signals the end of
a batch of Transact-SQL statements. A local variable is only valid within the
body of a batch or procedure.
Solution:
The first option is to remove the GO command between the 2
sets of scripts so that the local variable @numberOfCards is valid and
accessible on both scripts. Use semi comma where ever the sql statement ends.