I am using SQL Server 2008. I have two tables, Stock and Usage. The fields of the tables are like below
Stock table
|itemid |batch |qty |date |
---------------------------------------
|item1 |batch1 |20000 |2017-05-01 |
|item2 |batch1 |500 |2017-05-01 |
|item2 |batch2 |1000 |2017-05-02 |
|item2 |batch3_|1000 |2017-05-03 |
Usage table
|id |itemid |qty |
------------------------
|doc1 |item1 |8000 |
|doc1 |item2 |2000 |
|doc2 |item1 |500 |
I need to insert into other table where it will record what stock that have been used based on Usage table. I need to select the old stock first to be picked for the batch.
The desired table
|id |itemid |batch |qty |
-------------------------------------------
|doc1 |item1 |batch1 |8000 |
|doc1 |item2 |batch1 |500 |
|doc1 |item2 |batch2 |1000 |
|doc1 |item2 |batch3 |500 |
|doc2 |item1 |batch1 |500 |
I have come out with something like this. But how do I join the two tables. Or is there any other way to do this?
create usage_tmp
(
no int identity,
id nvarchar(20),
itemid nvarchar(20),
qty int
)
select no into #ControlTable
from usage_tmp
DECLARE @QTY INT,
@TABLEID INT,
@QTYBAL INT
SET @QTYBAL = 0
WHILE EXISTS (SELECT * FROM #ControlTable)
BEGIN
select top 1 @TableID = no
from #ControlTable
order by no asc
SET @QTY = (SELECT top 1 QTY FROM usage_tmp)
WHILE (@QTYBAL<@QTY)
BEGIN
INSERT INTO tbl_tmp
SELECT * from stock
END
delete #ControlTable
where no = @ID
end
drop table #ControlTable