SQL 错误:在多个数据库中插入语句的“必须声明标量变量”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7076801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: "Must declare the scalar variable" for insert statements in multiple database
提问by OnesimusUnbound
I created a SQL script to add an entry in different database. However, when I run the script through SQL Server Management Studio.
我创建了一个 SQL 脚本来在不同的数据库中添加一个条目。但是,当我通过 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'
必须声明标量变量“@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?
在这一点上,我完全困惑,因为我@address
在执行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.
到目前为止,我只是insert
为了完成任务才将实际值放入语句中,尽管我想知道是什么导致了错误。
回答by Preet Sangha
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.
变量@address 只存在于它定义的批处理中,批处理由 go 语句分隔,它超出了范围。
try this:
尝试这个:
declare @address varchar(50)
set @address = 'Hope'
insert into DB1.dbo.Address
values (@address)
insert into DB2.dbo.Address
values (@address)
go
回答by Paolo Falabella
回答by Guffa
It's because you are using go
between the statement that declares the variable and the statement that uses it.
这是因为您go
在声明变量的语句和使用它的语句之间使用。
The go
command is not an SQL command, it's a separator between sessions in Management Studio. Just remove all the go
commands in your query, and you can use the variable all the way.
该go
命令不是 SQL 命令,它是 Management Studio 中会话之间的分隔符。只需删除go
查询中的所有命令,就可以一直使用该变量。