title: CTE - recursively update quantity until total consumed
body: <p>I've been researching CTEs trying to determine if it's possible to recursively update inventory quantity records with an order quantity until the order quantity is consumed.</p>
  
  <p>Here are the tables and records:</p>
  
  <pre><code>CREATE TABLE [dbo].[myOrder](
    [Account] [float] NOT NULL,
    [Item] [float] NOT NULL,
    [Quantity] [float] NOT NULL
  ) ON [PRIMARY]
  
  insert into dbo.myOrder values (12345, 1, 50)
  
  CREATE TABLE [dbo].[myInventory](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [Account] [float] NOT NULL,
    [InvDate] [numeric](18, 0) NOT NULL,
    [Item] [float] NOT NULL,
    [Quantity] [float] NOT NULL,
    [QuantitySold] [float] NOT NULL
  ) ON [PRIMARY]
  
  insert into dbo.myInventory values (12345, 111287, 1, 45, 40)
  insert into dbo.myInventory values (12345, 111290, 1, 40, 0)
  insert into dbo.myInventory values (12345, 111290, 1, 12, 0)
  insert into dbo.myInventory values (12345, 111291, 1, 25, 0)
  </code></pre>
  
  <p>The record in the myOrder table indicates that an order is to be created for account 12345 for item #1, quantity 50:</p>
  
  <pre><code>Account Item Quantity 
  ------- ---- --------
  12345   1    50
  </code></pre>
  
  <p>The inventory table shows that we have plenty of item #1 on hand for account 12345:</p>
  
  <pre><code>ID Account InvDate Item Quantity QuantitySold
  -- ------- ------- ---- -------- ------------
  1  12345   111287  1    45       40
  2  12345   111290  1    40       0
  3  12345   111290  1    12       0
  4  12345   111291  1    25       0
  </code></pre>
  
  <p>The goal is to start plugging in the order quantity of 50 into the inventory records until all 50 are consumed. Inventory records are ordered by the value in the InvDate column. Record 1 has 5 remaining quantity (45 - 40 = 5), which would leave us with 45 more to consume for the order. Record 2 can consume 40. Record 3 can consume the last 5. When the query completes the inventory records would look like this: </p>
  
  <pre><code>ID Account InvDate Item Quantity QuantitySold
  -- ------- ------- ---- -------- ------------
  1  12345   111287  1    45       45
  2  12345   111290  1    40       40
  3  12345   111290  1    12       5
  4  12345   111291  1    25       0
  </code></pre>
  
  <p>Note: The inventory table stores QuantitySold, not QuantityRemaining, so you have to do the math (Quantity - QuantitySold) to determine how much quantity remains per inventory record.</p>
  
  <p>I've gotten almost nowhere with the CTE. I've found plenty of examples for doing selects where you have 2 parts to your CTE - an initialization part and the recursive part UNIONed together. I could write this with a cursor, but I think it's possible to do with a CTE and I'd like to learn how.</p>
  
  <p>If anyone can confirm this is possible with a CTE or explain how to set up the CTE, I'd appreciate it. Thanks!</p>