I think a better approach might be to join the Contact table on twice rather than joining it on different columns in one go, and then COALESCE'ing the results.
ie.
Code:
-- Left join on ID2
LEFT JOIN Contact CC1 (NOLOCK) ON CC1.ID3 = AG.ID1 AND ISNULL(AG.ID1,0) <> 0
LEFT JOIN Contact CC2 (NOLOCK) ON CC2.ID3 = AG.ID2 AND ISNULL(AG.ID1,0) = 0
-- and then everywhere you want Contact referenced, you use the one that isn't null like:
SELECT COALESCE(CC1.ContactName, CC2.ContactName) As ContactName
Hope this helps
edit:
give this a try as well (just uses 1 join):
Code:
LEFT JOIN Contact CC (NOLOCK)
ON CC.ID3 = CASE WHEN ISNULL(AG.ID1,0) = 0 THEN AG.ID2 ELSE AG.ID1 END