Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

SQL Server 2000 - "must declare variable '@ID'" after USE statement

Posted on 2009-02-12
3
Medium Priority
?
450 Views
Last Modified: 2012-05-06
I have a variable scoping problem.  The following (simplified) script generates 2 "Must declare the variable" errors.

What do I need to do to overcome the scope issue and use the variable against both DB's?

Thanks!

Msg 137, Level 15, State 2, Line 1
Must declare the variable '@ID'.
Msg 137, Level 15, State 2, Line 3
Must declare the variable '@ID'.
begin tran
 
Declare @ID int
Set @ID = 5
 
use Database1
go
Select @ID
go
 
use Database2
go
Select @ID
 
rollback tran

Open in new window

0
Comment
Question by:Daniel Wilson
3 Comments
 
LVL 39

Accepted Solution

by:
BrandonGalderisi earned 252 total points
ID: 23623442
GO terminates a batch and in this case is not necessary.  Any variable declared, goes out of scope with a GO is reached.



begin tran
 
Declare @ID int
Set @ID = 5
 
use Database1
Select @ID
 
use Database2
Select @ID
 
rollback tran

Open in new window

0
 
LVL 60

Assisted Solution

by:chapmandew
chapmandew earned 248 total points
ID: 23623456
remove your GO statements.
0
 
LVL 32

Author Closing Comment

by:Daniel Wilson
ID: 31546131
Well, that was easy enough!  Thanks!
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
Microsoft Access has a limit of 255 columns in a single table; SQL Server allows tables with over 255 columns, but reading that data is not necessarily simple.  The final solution for this task involved creating a custom text parser and then reading…
Familiarize people with the process of utilizing SQL Server functions from within Microsoft Access. Microsoft Access is a very powerful client/server development tool. One of the SQL Server objects that you can interact with from within Microsoft Ac…
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

571 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question