Comment créer un LEFT JOIN conditionnel?

J'essaie de GAUCHER JOIN 3 arrays comme ça:

DECLARE @CustomerID AS INT; DECLARE @ProductID AS INT; SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id LEFT JOIN table3 t3 ON t2.loc = t3.loc WHERE t1.id = @ProductID AND (t2.loc = t3.loc OR t2.loc IS NULL) AND (t3.cid = @CustomerID OR t3.cid IS NULL) 

Il y a 4 cas de base que j'essaie de résoudre:

  1. @CustomerID <> 0 et @ProductID existe uniquement dans t1
  2. @CustomerID <> 0 et @ProductID existe dans t1 et t2
  3. @CustomerID = 0 et @ProductID n'existe que dans t1
  4. @CustomerID = 0 et @ProductID existe dans t1 et t2

Le code ci-dessus fonctionne pour les cas 1-3, mais ne renvoie rien dans le cas 4. Je pense que c'est parce que le dernier LEFT JOIN se brise (même si datatables existent à la fois dans t1 et t2 pour ce @ProductID).

Existe-t-il un moyen de conditionner la seconde LEFT JOIN sans utiliser la logique IF … ELSE?

Placez les conditions dans la clause on au lieu de la clause where

 SELECT * FROM table1 t1 LEFT JOIN table2 t2 ON t1.id = t2.id LEFT JOIN table3 t3 ON t2.loc = t3.loc AND (t3.cid = @CustomerID OR t3.cid IS NULL) AND (t2.loc = t3.loc OR t2.loc IS NULL) WHERE t1.id = @ProductID 

Si je comprends ce que vous voulez, cela pourrait fonctionner:

 SELECT * FROM table1 a LEFT JOIN table2 b ON b.id = a.id LEFT JOIN table3 c ON c.loc = b.loc and isNull(c.cid, @CustomerID) = CustomerID WHERE t1.id = @ProductID