错误:“必须声明标量变量"用于在多个数据库中插入语句 [英] Error: "Must declare the scalar variable" for insert statements in multiple database
问题描述
我创建了一个 SQL 脚本来在不同的数据库中添加一个条目.但是,当我通过 SQL Server Management Studio 运行脚本时.
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
我收到以下错误:
必须声明标量变量'@address'
Must declare the scalar variable '@address'
此时,我完全糊涂了,因为我在执行 insert
语句之前已经声明了变量 @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?
到目前为止,我只是为了完成任务而将实际值放入 insert
语句中,尽管我想知道是什么导致了错误.
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.
推荐答案
变量@address 只存在于它定义的批次中,批次由 go 语句分隔,超出范围.
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.
试试这个:
declare @address varchar(50)
set @address = 'Hope'
insert into DB1.dbo.Address
values (@address)
insert into DB2.dbo.Address
values (@address)
go
这篇关于错误:“必须声明标量变量"用于在多个数据库中插入语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!