"Must declare the scalar variable" 在 SQL 中尝试 运行 UPDATE 语句时

"Must declare the scalar variable" when trying to run UPDATE statement in SQL

尝试使用两个 table 变量(@NameZip@NameZip2)更新两个 table(CityLocation)。城市名称有 ZipCodesZipCodesNames,反之亦然。更新正在更改错误输入的城市名称和邮政编码。但是出现错误:

Msg 137, Level 16, State 1, Line 28
Must declare the scalar variable "@NameZip2".

Msg 137, Level 16, State 1, Line 32
Must declare the scalar variable "@NameZip".

我写的查询:

--first table variable
DECLARE @NameZip TABLE 
                 (
                     Zip_Code NVARCHAR(100),
                     Name NVARCHAR(100),
                     id_city INT
                 )

--second table variable
DECLARE @NameZip2 TABLE
                  (
                      Zip_Code nvarchar(100),
                      Name NVARCHAR(100),
                      id_city INT
                  )

--inserting into first table variable from City and Location table
INSERT INTO @NameZip (Zip_code, Name, id_city)
    SELECT B.Zip_Code, A.Name, A.id_city
    FROM City A 
    INNER JOIN Location B ON A.id_city = B.id_city 
                          AND Name NOT LIKE '%[^0-9]%'

--inserting into second table variable from first table variable
INSERT INTO @NameZip2(Zip_code, Name, id_city)
    SELECT Name, Zip_Code, id_city
    FROM @NameZip

UPDATE City 
SET Name = (SELECT Name FROM @NameZip2)
WHERE City.id_city = @NameZip2.id_city -- I get error on this line

UPDATE Location
SET Zip_Code = (SELECT Zip_Code FROM @NameZip2)
WHERE Zip_Code = @NameZip.Zip_Code -- I get error on this line

如有任何意见,我们将不胜感激。

使用update from join语法

update c
set Name = z.Name 
from City C
inner join @NameZip2 z on c.id_city =z.id_city 

location table 更新也做同样的事情。

您想通过联接来执行此操作...但是您的 table 变量并不是真正需要的。

update c
set c.Name = n.Name
from City c
inner join @NameZip2 n on n.id_city = c.id_city

update L
set L.Zip_Code = n.Zip_Code
from Location L
inner join
@NameZip2 n on n.Zip_Code = L.Zip_Code

可以写成...

update c
set c.Name = n.Name, c.Zip_Code = n.Zip_Code
from City c
inner join    
    (SELECT B.Zip_Code, A.Name, A.id_city
    FROM City A 
    INNER JOIN Location B ON A.id_city = B.id_city 
                          AND Name NOT LIKE '%[^0-9]%') n

虽然其他答案可以帮助您更改代码,但我认为解释代码的问题很有趣:

SET Name = (SELECT Name FROM @NameZip2)

这一行可能会给您带来错误。如果您使用 = 运算符,则必须确保表达式 return 只有一个值。即使你是对的,@NameZip2 只有一个记录,这也不是一个好方法,你可以这样做:

SET Name = (SELECT Top 1 Name FROM @NameZip2)

还有这一行:

WHERE Zip_Code = @NameZip.Zip_Code

将不起作用,因为@NameZip 是 table,您应该使用 SELECT 命令而不是 =,这样:

WHERE Zip_Code = (SELECT TOP 1 Zip_Code FROM @NameZip)