Reputation: 83
I have a SQL join that looks like this
INNER JOIN UPLOAD PH on cast(p.PickTicket_Number as varchar(20))=PH.FIELD004
However, sometimes, the field I really want to join on is PH.FIELD003. This happens when PH.FIELD004 is a different field that has letters in it. How do I include a condition in the ON clause where if field004 does not have letters in it (is numeric), it joins just like that above, but if it does have letters in it, it instead joins on the pickticket number = field003?
Upvotes: 0
Views: 43
Reputation: 1271061
You can express the logic like this:
UPLOAD PH
ON cast(p.PickTicket_Number as varchar(20)) = PH.FIELD004 OR
(TRY_CONVERT(int, PH.FIELD004) IS NULL AND
CAST(p.PickTicket_Number as varchar(20)) = PH.FIELD003
)
Notes:
FIELD004
cannot be converted to an INT
. This is hopefully close enough to "has letters in it". If not, you can use a CASE
expression with LIKE
.OR
is a performance killer for JOIN
conditions. Function calls (say for conversion) also impede the optimizer.INT
; if not, change to the appropriate type.Because of the last issue, I would recommend:
UPLOAD PH
ON TRY_CONVERT(INT, PH.FIELD004) = p.PickTicket_Number OR
(TRY_CONVERT(int, PH.FIELD004) IS NULL AND
p.PickTicket_Number= PH.FIELD003
)
Upvotes: 2