DECLARE @Product table(ProductID int)DECLARE @ProductRelation TABLE (FirstProductID int,SecondProductID int)INSERT INTO @Product SELECT 1UNION ALLSELECT 2UNION ALLSELECT 3UNION ALLSELECT 4UNION ALLSELECT 5UNION ALLSELECT 6UNION ALLSELECT 7UNION ALLSELECT 8UNION ALLSELECT 9UNION ALLSELECT 10--SELECT * FROM @ProductINSERT INTO @ProductRelationSELECT 1,2UNION ALLSELECT 3,5UNION ALLSELECT 2,6UNION ALLSELECT 1,4UNION ALLSELECT 1,4--SELECT * FROM @ProductRelation SELECT ProductID,'Not Linked' AS 'Relation' FROM @ProductUNIONSELECT FirstProductID,'Linked' from @ProductRelationUNIONSELECT SecondProductID ,'Linked' FROM @ProductRelation
ProductID Relation1 Linked2 Linked3 Linked4 Linked5 Linked6 Linked7 Not Linked8 Not Linked9 Not Linked10 Not Linked
SELECT p.ProductID, Relation = CASE x.n WHEN 1 THEN 'Linked' ELSE 'Not Linked' ENDFROM @Product pOUTER APPLY ( SELECT TOP 1 n=1 FROM @ProductRelation r WHERE p.ProductID IN (r.FirstProductID, r.SecondProductID)) xORDER BY p.ProductID
SELECT p.ProductID, CASE WHEN EXISTS(SELECT 1 FROM @ProductRelation pr WHERE p.ProductID IN (pr.FirstProductID, pr.SecondProductID)) THEN 'Linked' ELSE 'Not Linked' ENDFROM @Product pORDER BY p.ProductID
SELECT p.ProductID, CASE WHEN R1.FirstProductID IS NULL and R2.SecondProductID IS NULL then 'Not Linked' ELSE 'Linked' END Relation FROM @Product p LEFT JOIN @ProductRelation R1 ON R1.FirstProductID = p.ProductID LEFT JOIN @ProductRelation R2 ON R2.SecondProductID= p.ProductIDORDER BY p.ProductID
SELECT p.ProductID, CASE WHEN R.FirstProductID IS NULL and R.SecondProductID IS NULL then 'Not Linked' ELSE 'Linked' END Relation FROM @ProductRelation R RIGHT JOIN @Product p ON p.ProductID = R.FirstProductID OR p.ProductID = R.SecondProductIDORDER BY p.ProductID