根据列值动态决定连接表

时间:2016-11-29 19:06:56

标签: sql sql-server dynamic inner-join

我想动态内连接表,这是我的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

我可以通过上述方式或任何其他选择来决定吗?

如果是,怎么样?

1 个答案:

答案 0 :(得分: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