2017-05-18 2 views
1

Ich habe eine Update Abfrage, wo die from Tabelle ist die gleiche wie eine der Join-Tabellen. Es sieht so etwas wie diesesUpdate-Abfrage, die gleiche hat Von und Join Tabelle Berichterstattung Mehrdeutige Tabelle Fehler

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> 

Wenn ich laufen diese, ich kann ein Fehler, der The table 'Contacts' is ambiguous heißt, was bedeutet, dass ich nicht die gleiche Tabelle zweimal in meinem Update-Abfrage enthalten. Also, wie soll ich dieses Update machen (oder gibt es einen Weg dazu)?

+0

Wie lauten die Quoten: 'ct.ClientId = ct.ClientId'? Es scheitert an Nullen. – HABO

Antwort

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


können Sie unter Abfrage verwenden, als auch

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>; 

Während Versuch Aktualisierung MERGE-Funktion zu verwenden, anstatt verbindet

0

ich in der Lage war, dies zu lösen, indem sie den gesamten from...join Teil der Herstellung Abfrage in eine verschachtelte Unterabfrage und dann trat diese stattdessen bei. So sieht das Endergebnis folgendermaßen aus:

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 
Verwandte Themen