尝试在SQL中运行UPDATE语句时“必须声明标量变量”

时间:2018-04-06 16:26:51

标签: sql-server sql-update table-variable

尝试使用两个表变量(CityLocation)更新两个表(@NameZip@NameZip2)。城市名称ZipCodesZipCodes都有Names,而不是相反。更新正在更改错误输入的城市名称和ZipCodes。但得到错误:

  

Msg 137,Level 16,State 1,Line 28
  必须声明标量变量“@ NameZip2”。

     

Msg 137,Level 16,State 1,Line 32
  必须声明标量变量“@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

任何有关此事的意见都将受到赞赏。

3 个答案:

答案 0 :(得分:3)

使用update from join语法

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

同样为location表更新执行相同操作。

答案 1 :(得分:2)

您希望通过连接执行此操作...但实际上并不需要您的表变量。

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

答案 2 :(得分:1)

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

SET Name = (SELECT Name FROM @NameZip2)

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

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

这一行:

WHERE Zip_Code = @NameZip.Zip_Code

因为@NameZip是一个表而无法工作,你应该使用SELECT命令而不是=,这样:

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