Reputation: 1626
How can I modify the join clause with a case clause; for example I want the table to join another column if column1 is null such as:
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON
CASE WHEN MYTABLE.A IS NULL THEN MYTABLE.B = OTHERTABLE.A
ELSE MYTABLE.A IS NOT NULL THEN MYTABLE.A = OTHERTABLE.A
(totally made that up,sorry for syntax errors :))
Upvotes: 0
Views: 104
Reputation: 3223
Just try below code :
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON OTHERTABLE.A = isnull(MYTABLE.A,MYTABLE.B)
Upvotes: 1
Reputation: 18559
SELECT * FROM MYTABLE
LEFT JOIN OTHERTABLE ON COALESCE(MYTABLE.A, MYTABLE.B) = OTHERTABLE.A
Upvotes: 1
Reputation: 17590
Try this one:
SELECT *
FROM MyTable M
LEFT JOIN OtherTable O ON(CASE WHEN M.A IS NULL THEN M.B ELSE M.A END) = O.A
Upvotes: 4