表A
name, street, city, state, zip
bill, 123 main, newcity, null, 77777
bill, 123 main, newcity, null, 77777
fred, 23 west, greattown, null, 12345
bob, 4 a St, nowhere, null, 34567
表B
name, street, city, st, zip
bill, 123 main, newcity, me, 77777
bill, 123 main, newcity, me, 77777
fred, 23 west, greattown, ny, 12345
bob, 4 a St, nowhere, wy, 34567
我想做
update table A
set state = tB.st
from
table A tA inner join table B tB
on (tA.name = tB.name and tA.street = tB.street)
但我不想更新2条记录“bill,123 main,newcity,null,77777”。
如何从表格中排除这些行?
由于 查尔斯
答案 0 :(得分:1)
在SQL Server 2005+中,您可以执行以下操作:
;
WITH A_counted AS (
SELECT
*,
cnt = COUNT(*) OVER (PARTITION BY name, street, city, zip)
FROM TableA
), B_counted AS (
SELECT
*,
cnt = COUNT(*) OVER (PARTITION BY name, street, city, zip)
FROM TableB
)
UPDATE A_counted
SET state = B.state
FROM B_counted B
WHERE A_counted.name = B.name,
AND A_counted.street = B.street,
AND A_counted.city = B.city,
AND A_counted.zip = B.zip
AND A_counted.cnt = 1
AND B.cnt = 1
答案 1 :(得分:0)
我看到它的方式是:
1)创建一个临时表,其中A中的记录不止一次出现。
2)创建第二个临时表,其中B中的所有记录与步骤1中的临时表中的记录不匹配。
3)更新步骤2中的所有记录。
答案 2 :(得分:0)
你应该只需要为你的加入增加1个条件:
update table A
set state = tB.st
from
table A tA inner join table B tB
on (tA.name = tB.name and tA.street = tB.street and tA.name <> 'Bill')
这应该排除那两行甚至被更新语句看到。