Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error: "Must declare the scalar variable" for insert statements in multiple database

I created a SQL script to add an entry in different database. However, when I run the script through SQL Server Management Studio.

declare @address varchar(50)
set @address = 'Hope'

use DB1
go

insert into Address
 values (@address)
go

use DB2
go

insert into Address
 values (@address)
go

I got the following error:

Must declare the scalar variable '@address'

At this point, I'm totally confused because I've declared the variable @address before executing the insert statement. Is it because I'm traversing different database?

As of now, I've just put the actual value in the insert statement just for the sake of completing the task, though I wondered what caused the error.

like image 662
OnesimusUnbound Avatar asked Aug 16 '11 10:08

OnesimusUnbound


2 Answers

the variable @address only lives in the batch that its defined in, batches are delimited by the the go statement, where it goes out of scope.

try this:

declare @address varchar(50)
set @address = 'Hope'

insert into DB1.dbo.Address
 values (@address)

insert into DB2.dbo.Address
 values (@address)
go
like image 158
Preet Sangha Avatar answered Oct 11 '22 17:10

Preet Sangha


It's the GO statement.

all local variable declarations must be grouped in a single batch. This is done by not having a GO command until after the last statement that references the variable. (from MSDN)

like image 22
Paolo Falabella Avatar answered Oct 11 '22 18:10

Paolo Falabella