尝试更新同一列/表的多个数据库

时间:2018-07-06 17:50:23

标签: sql sql-server tsql

我正在尝试更新多个数据库中的同一表/列,并获取其中的3个必须为@new_accountnumber声明标量值。试图弄清楚我在做什么错。

代码

DECLARE @Old_AccountNumber nvarchar(20)
DECLARE @New_AccountNumber nvarchar(20)
SET @Old_AccountNumber = ('TX000000')
SET @New_AccountNumber = ('ZZTX000000')

USE [HQDB]
UPDATE Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber
GO

USE [HGSDB3]
UPDATE Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber
GO

USE [Warehouse3]
UPDATE Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber
GO

USE [Stationery]
UPDATE Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber
GO

错误:

  

137级第2州第14行的消息137   必须声明标量变量“ @New_AccountNumber”。
  消息137,第15级,州2,第20行
  必须声明标量变量“ @New_AccountNumber”。
  消息137,第15级,州2,第26行
  必须声明标量变量“ @New_AccountNumber”。

2 个答案:

答案 0 :(得分:2)

您的GO命令正在结束update操作的作用域或结束已声明的变量作用域。因此,只需删除GO命令。

答案 1 :(得分:0)

如果需要,您也可以简化一点。您不必添加USE语句即可访问另一个数据库。只需完全限定对该表的引用即可。您可以像这样进行这些更新。

DECLARE @Old_AccountNumber nvarchar(20)
DECLARE @New_AccountNumber nvarchar(20)
SET @Old_AccountNumber = ('TX000000')
SET @New_AccountNumber = ('ZZTX000000')

UPDATE HQDB.dbo.Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber

UPDATE HGSDB3.dbo.Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber

UPDATE Warehouse3.dbo.Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber

UPDATE Stationery.dbo.Customer
SET AccountNumber = @New_AccountNumber
WHERE AccountNumber = @Old_AccountNumber