Search code examples
sql-serverinner-join

How to handle a join with two potential columns


I have a straight forward sql statement that joins a few tables to get some metadata about the items in a container. The issue I have is that tableTwo now has a field that supersedes productid (let's call it masterProductId) if it's populated and we would therefor want to join one.productid on that column instead for that row. If masterProductId is not used it's normally left empty, but not null. I'm not sure how to handle the potentially different joins in one statement. Here's the bones of the statement without an attempt to add in masterProductId

select distinct one.code from tableOne one
inner join tableTwo two on two.productid = one.productid
inner join tableThree three on three.itemguid = two.itemguid
where three.wrhscontrid = @containerId
and one.statecode = '' 

Solution

  • So let me restate this:

    1. Table Two has masterProductKey.
    2. If it has a value in it then use that to join to Product.
    3. If not then join with product key

    Here is the solution:

    join tableTwo two 
          on case when masterProductKey!='' 
                  then masterProductKey 
                  else two.productid end = one.ProductID