2017-07-25 167 views
0

我正在使用SQL Server 2008.我有兩個表格,Stock和Usage。該表的字段是像下面SQL - 根據其他表插入到表

股票表

|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 | 

使用表

|id |itemid |qty | 
------------------------  
|doc1 |item1 |8000 | 
|doc1 |item2 |2000 | 
|doc2 |item1 |500 | 

我需要插入到其他表,其中它會記錄什麼股票已經根據用量表使用。我需要首先選擇舊的庫存以供批處理。

所需的表

|id  |itemid   |batch  |qty | 
------------------------------------------- 
|doc1 |item1   |batch1  |8000 | 
|doc1 |item2   |batch1  |500 | 
|doc1 |item2   |batch2  |1000 | 
|doc1 |item2   |batch3  |500 | 
|doc2 |item1   |batch1  |500 | 

我已經推出了這樣的事情。但我如何加入這兩張桌子。或者有沒有其他方法可以做到這一點?

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 
+0

[如何在sql中實現FIFO]可能的重複(https://stackoverflow.com/questions/25152990/how-to-implement-fifo-in-sql) – Serg

回答

0

僅有兩張表中沒有足夠的信息來系統地加入它們並解決此問題。