2016-11-29 21 views
1

我要動態地內連接表,這是我的SQL查詢動態決定加入基於表中的列值

Update temp 
Set temp.Order_Id = parent.ID 

from #TempTransactions AS temp 

Inner Join (case when temp.OrderType = 1 then preorders else orders end) AS parent 

ON parent.Cloud_Id = temp.Order_Id 

是否有可能,我可以在上面的方式或任何其他可替代決定?

如果是,如何?

回答

2

兩個左連接可以。

Update temp Set temp.Order_Id = COALESCE(p.ID, o.ID) 

from #TempTransactions AS temp 

LEFT Join preorders p ON p.Cloud_Id = temp.Order_Id AND temp.OrderType=1 
LEFT JOIN orders o ON o.Cloud_Id = temp.Order_Id AND (temp.OrderType <> 1 OR temp.OrderType IS NULL) 
WHERE COALESCE(p.ID, o.ID) IS NOT NULL