-- Here's the last change.
USE [Build1]
SELECT
td.TYPE_NAME
,i.DOC_NAME
,i.DOC
,i.SEC
,i.VER
,r.JUSTIFICATION
FROM TBL_INSTANCES i
INNER JOIN TBL_TYPE_DEF td
ON i.TYPE_ID = td.TYPE_ID
LEFT JOIN TBL_RELATIONSHIPS r
ON i.DOC = r.PARENT_DOC
AND i.SEC = r.PARENT_SEC
AND i.VER = r.PARENT_VER
-- simplification
WHERE NOT EXISTS (
SELECT 1
FROM TBL_RELATIONSHIPS ri
WHERE ri.PARENT_DOC = i.DOC
AND ri.PARENT_SEC = i.SEC
AND ri.PARENT_VER = i.VER
AND ri.CHILD_DOC IS NOT NULL
)
-- simplification
AND i.TYPE_ID NOT IN (SELECT CHILD_TYPE FROM TBL_RELATIONSHIPS_ALLOWED)
ORDER BY td.TYPE_ID
,i.DOC
,i.SEC
,i.VER
For fast, accurate and documented assistance in answering your questions, please read this article.
Understanding and using APPLY, (I) and (II) Paul White
Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden