带有内部联接和子字符串的SQL Update行

时间:2015-01-19 16:51:18

标签: sql join sql-update substring

我试图根据邮政编码更新a_customer_test表中的城镇列。

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  

1 个答案:

答案 0 :(得分:0)

所以你想用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)