我正在将数据从一个表转移到另一个表。
旧表曾经有一个名为City的varchar列。
新表(而不是城市名称)具有一个名为CityId的int列,因为我仅为城市创建了新表。
“我的城市”表具有以下列:
CityID - PK
RegionID - FK
CityName - Varchar(50)
我正在运行此查询以复制新表的旧数据:
INSERT INTO dbo.Client(EmailAddress, CityID)
a.EmailAddress, (SELECT CityID FROM Cities WHERE CityName collate SQL_Latin1_General_CP1_CI_AS = a.City)
FROM AdventureWorksOld.dbo.Client a
但是我不能这样做,因为子查询返回多行:
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
如何修复我的代码,以便可以执行以下操作:
SELECT (SELECT CityName FROM Cities WHERE CityName = 'Oak Bay') -> Replace 'Oak Bay' with the text in the column
FROM AdventureWorksOld.dbo.Client
谢谢。
答案 0 :(得分:-1)
这可能是您在寻找什么?
INSERT INTO dbo.Client(EmailAddress, CityID)
SELECT
a.EmailAddress
, c.CityID
FROM AdventureWorksOld.dbo.Client a
LEFT JOIN Cities c ON c.CityName = a.City
答案 1 :(得分:-1)
尝试一下:
INSERT INTO dbo.Client(EmailAddress, CityID)
SELECT
a.EmailAddress
, c.CityID
FROM AdventureWorksOld.dbo.Client a
OUTER APPLY (SELECT TOP 1 c.CityID FROM Cities c WHERE c.CityName = a.City) c