Trying to update two tables (City
and Location
) using two table variables (@NameZip
, @NameZip2
). The city names have ZipCodes
and ZipCodes
have Names
instead of vice versa. Updates are changing City names and ZipCodes where they were wrongly entered. But getting the error:
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".
The query I wrote:
--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
Any inputs regarding this would be appreciated.