SQL 使用带子字符串的内部连接更新行

SQL Update row with inner join with substring

我正在尝试根据他们的邮政编码更新 a_customer_test table 中的城镇栏。

select 语句工作正常

SELECT * FROM dbo.postcodes b with(nolock)
left join  a_customer a with(nolock)
on SUBSTRING ( a.postcode,1,3) =  SUBSTRING ( b.postcode,1,3) 

但是当我对查询应用相同的逻辑并更新查询时,它不会工作 运行 但不会更新任何内容。

UPDATE
a_customer_test 
SET
a_customer_test.town = b.town
FROM dbo.postcodes b   with(nolock)
left join  a_customer a  with(nolock) 
on SUBSTRING ( b.postcode,1,3) =  SUBSTRING ( a.postcode,1,3)

* 工作查询 *

UPDATE
a_customer_test 
SET
a_customer_test.town = b.town
FROM dbo.postcodes b with(nolock) 
left join  a_customer_test a with(nolock) 
on SUBSTRING ( a.postcode,1,3) =  SUBSTRING ( b.postcode,1,3)
WHERE SUBSTRING ( b.postcode,1,3) = SUBSTRING ( a.postcode,1,3) 
AND a.postcode is not null  

所以您想用 b.town 中的一个值更新 a_customer_test 的所有 [town] 列?我认为您需要加入 a_customer_test 并相应地更新其列..

如果您想在找到匹配项时填充 [town],则只需指定一个值来更新。例如使用SELECT TOP 1

UPDATE
a_customer_test 
SET
a_customer_test.town = 
(SELECT TOP 1 b.town
FROM dbo.postcodes b   with(nolock)
left join  a_customer a  with(nolock) 
on SUBSTRING ( b.postcode,1,3) =  SUBSTRING ( a.postcode,1,3)
WHERE a.postcode IS NOT NULL)