1

I have a simple query that uses the following command text to return values from a SQL Server to an Excel sheet. However, when the Material value is not found in the Material_Location table, it simply omits it.

How can I modify the following code to return the value of On_Hand_Qty as "0", if the Material is not found in the Material_Location table

    SELECT
      SO_Detail.Sales_Order,
      SO_Detail.SO_Line,
      SO_Detail.Material,
      SO_Detail.Order_Qty,
      Material_Location.On_Hand_Qty
     FROM
      SO_Detail
      INNER JOIN Material_Location ON SO_Detail.Material = Material_Location.Material
    ORDER BY
      SO_Detail.Sales_Order,
      SO_Detail.SO_Line

Thanks

5
  • Is this what you're looking for? ifnull(Material_Location.On_Hand_Qty,0) Commented Nov 7, 2017 at 16:51
  • There is a lot of ways to do it, using CASE, ISNULL, IIF, COALESCE Commented Nov 7, 2017 at 16:53
  • @Sami - before that we need Left Outer Join to get the non matching record Commented Nov 7, 2017 at 16:54
  • Use a left join Commented Nov 7, 2017 at 16:54
  • @Pரதீப் Yeah, that's right. Commented Nov 7, 2017 at 17:22

1 Answer 1

2

Using a left outer join instead of inner join will allow you to still get records from SO_Detail even when no matching record exists in Material_Location.

COALESCE will go through each parameter passed to it until it finds one that is not null

SELECT
  sd.Sales_Order,
  sd.SO_Line,
  sd.Material,
  sd.Order_Qty,
  COALESCE(ml.On_Hand_Qty,0) as On_Hand_Qty
 FROM
  SO_Detail sd
  LEFT OUTER JOIN Material_Location ml ON sd.Material = ml.Material
ORDER BY
  sd.Sales_Order,
  sd.SO_Line
Sign up to request clarification or add additional context in comments.

3 Comments

@Pரதீப் not sure what you mean?
@gordatron - Query looks lot better now :) +1
@Pரதீப் i was wondering if that was what you meant :D all those characters just too much for you? if i had not copied and pasted i would not have been able to bring myself to type that all out XD

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.