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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:42:11  来源:igfitidea点击:

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

sqlsql-serversql-server-2005scope

提问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 @addressbefore executing the insertstatement. Is it because I'm traversing different database?

在这一点上,我完全困惑,因为我@address在执行insert语句之前已经声明了变量。是因为我正在遍历不同的数据库吗?

As of now, I've just put the actual value in the insertstatement 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

It's the GO statement.

这是 GO 语句。

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)

所有局部变量声明必须归为一个批次。这是通过在引用变量的最后一条语句之后才使用 GO 命令来完成的。(来自 MSDN

回答by Guffa

It's because you are using gobetween the statement that declares the variable and the statement that uses it.

这是因为您go在声明变量的语句和使用它的语句之间使用。

The gocommand is not an SQL command, it's a separator between sessions in Management Studio. Just remove all the gocommands in your query, and you can use the variable all the way.

go命令不是 SQL 命令,它是 Management Studio 中会话之间的分隔符。只需删除go查询中的所有命令,就可以一直使用该变量。