我正在使用SQL Server 2008.我有两个表,Stock和Usage。表格的字段如下所示
股票表
|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 |
我需要插入到其他表中,它会记录根据Usage表使用的库存。我需要先选择旧库存来批量生产。
所需的表格
|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 :(得分:0)
仅仅在两个表中没有足够的信息来系统地加入它们并解决这个问题。