title: TSQL Loop through table records and compare against 2nd table
body: <p>I have two temp tables, both populated by TSQL queries.</p>
  
  <p><strong>Temp Table A</strong> containing a Location, an Item, and a total inventory count.</p>
  
  <p><strong>Temp Table B</strong> containing a Location, an Item, a Sales Order Number, and negative inventory count.</p>
  
  <p>I would like to loop through each item in <strong>Table B</strong> and subtract the negative inventory count from table A where the location and item match.   Once the inventory reaches &lt;=0 in Table B, I want to output each order into a 3rd table which holds the Location, Item, and Sales Order Number.</p>
  
  <p>EXAMPLE TABLE A</p>
  
  <pre><code>Item|Location|Inventory
  1    A        10
  2    B        20
  </code></pre>
  
  <p>EXAMPLE TABLE B</p>
  
  <pre><code>Order|Item|Location|QuanityUsed
  ABC  |1   |A       |5
  ZYX  |2   |B       |10
  DEF  |1   |A       |6
  </code></pre>
  
  <p>DEF would be output into TABLE C because there is not enough inventory to fill the order after subtracting order ABC.</p>
  
  <p>How can I accomplish this?</p>