[英]SQL - Insert into table based on other table
I am using SQL Server 2008. I have two tables, Stock and Usage. 我正在使用SQL Server2008。我有两个表,库存和使用率。 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
仅两个表中没有足够的信息来系统地连接它们并解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.