我有一个Update
查询,其中from
表与其中一个连接表相同。它看起来像这样
Update Contacts
Set NewContactId = repCt.Id
From Contacts ct
Join Contacts repCt on repCt.ClientId = ct.ClientId
AND <a bunch of other join criteria>
Where <a bunch of other criteria hitting both ct and repCt>
当我运行此命令时,我会发出一条错误,指出The table 'Contacts' is ambiguous
,这意味着我无法在Update查询中包含两次相同的表。那么我应该如何进行此更新(或者有解决方法)?
答案 0 :(得分:1)
Update ct --use the alias defined in from
Set NewContactId = repCt.Id
From Contacts ct
Join Contacts repCt on ct.ClientId = repCt.ClientId
AND <a bunch of other join criteria>
Where <a bunch of other criteria hitting both ct and repCt>
答案 1 :(得分:1)
您也可以使用以下查询
MERGE INTO Contacts ct
USING Contacts repCt
ON (ct.ClientId = ct.ClientId
AND <a bunch of other join criteria>)
WHEN MATCHED THEN
SET NewContactId = repCt.Id
WHERE <a bunch of other criteria hitting both ct and repCt>;
更新时尝试使用MERGE函数而不是加入
答案 2 :(得分:0)
我能够通过将查询的整个from...join
部分放入一个嵌套的子查询中来解决这个问题,然后将其加入。所以最终结果如下:
Update Contacts
Set NewContactId = t.newId
From Contacts ct
Join (
select ct.Id, r.Id
from contacts ct
join contacts r on ct.clientid = r.clientid
<all of the joins>
) as t on ct.Id