考虑到我们有以下查询:
SELECT ca.Uid Numb,
ag.Code Cd,
ag.Name agn,
ca.TypeId tt
FROM dbo.Event ce
OUTERAPPLY
(SELECT*FROM dbo.Table1 tca WHERE tca.Uid= ce.Cuid) ca
OUTERAPPLY
(SELECT*FROM dbo.Table2 tct WHERE tct.Uid= ca.TypeId) ct
OUTERAPPLY
(SELECT*FROM dbo.Table3 ta WHERE ta.Id = ca.AgId) ag
OUTERAPPLY
(SELECT*FROM dbo.Table4 tsa WHERE tsa.Uid= ce.SId) ser
OUTERAPPLY
(
--- if Rows exists in this table take it
SELECT *
FROM dbo.Table5 ttra
WHERE ttra.ReferenceId = ce.TransactionRef
--- Otherwise use this table
SELECT *
FROM dbo.Table6 ttra
WHERE ttra.ReferenceId = ce.TransactionRef
) trx
WHERE trx.ApprovalDateTime ISNOTNULL
如果使用行ttra.ReferenceId = ce.TransactionRef
中存在行,我基本上希望在外部应用一个table5
否则在相同条件下使用Table6
答案 0 :(得分:1)
您似乎缺少空格,所以我插入了它们。
从使用OUTER APPLY的方式来看,最好使用LEFT JOIN(更具可读性)。如果需要分别为每个左行值评估右部分,则OUTER APPLY很有用,在前4个联接中似乎并非如此。
我不确定Table5 + Table6的联接,所以我把它留在那里。但也许也可以将其转换为LEFT JOIN。
此外,我使用UNION + NOT EXISTS将Table5中的行与Table6-if-Table5-gives-no-results中的行连接起来。
结果代码:
SELECT ca.Uid Numb,
ag.Code Cd,
ag.Name agn,
ca.TypeId tt
FROM dbo.Event ce
LEFT JOIN dbo.Table1 ca ON ca.Uid = ce.Cuid
LEFT JOIN dbo.Table2 ct ON ct.Uid = ca.TypeId
LEFT JOIN dbo.Table3 ag ON ag.Id = ca.AgId
LEFT JOIN dbo.Table4 se ON se.Uid = ce.SId
OUTER APPLY
(
--- if Rows exists in this table take it
SELECT *
FROM dbo.Table5 t5
WHERE t5.ReferenceId = ce.TransactionRef
UNION
--- Otherwise use this table
SELECT *
FROM dbo.Table6 t6
WHERE t6.ReferenceId = ce.TransactionRef
AND NOT EXISTS (SELECT 1 FROM dbo.Table5 WHERE ReferenceId = ce.TransactionRef)
) trx
WHERE trx.ApprovalDateTime IS NOT NULL