I have table with orders and table with stock. The oldest stock(stock_id) must fill up the oldest orders (order_id) for appropriate item.I have created some test data and the required result. The logic is obvious from example.
CREATE TABLE dbo.order_item (order_id INT, item_id CHAR(1), q INT) INSERT INTO order_item(order_id, item_id, q) VALUES (1,'A', 10), (2,'A', 5), (3,'B', 7), (4,'A', 6),(5,'B', 2) CREATE TABLE dbo.stock (stock_id INT, item_id CHAR(1), q INT) INSERT INTO stock(stock_id, item_id, q) VALUES (1,'A', 14), (2,'B', 5), (3,'A', 4), (4,'A', 12),(5,'B', 8)
The required result should be:
order_id item_id stock_id q_take 1 A 1 10 2 A 1 4 2 A 3 1 3 B 2 5 3 B 5 2 4 A 3 3 4 A 4 3 5 B 5 2
So, the oldest order is order_id 1, which need to take 10 from stock. And the oldest stock is stock with ID=1, which has the 14 on stock. The second oldest is order with ID=2, which need to take 5 from stock. 4 is left on stock with id=1, and 1 is taken from stock with id=3. And so on.....
The query should be without cursors, probably with CTE.