从SELECT语句INSERT INTO多个表

时间:2013-11-21 16:01:30

标签: sql sql-server

我有一个名为GoodsInOld的表,其中包含4列:

GoodsInOld:     Id, CustomerAccount, CustomerName, ItemId

由于新的数据结构,我创建了2个新表来保存数据:

GoodsInGoodsInProduct

他们有如下关系:

GoodsIn:        Id, CustomerAccount, CustomerName ...
GoodsInProduct: Id, ItemId, GoodsInId ...

GoodsIn可能有1个或多个GoodsInProduct

我想使用GoodsInOldINSERT INTOSELECT INTO中的数据插入到这两个表中?

1 个答案:

答案 0 :(得分:2)

insert into GoodsIn (CustomerAccount, CustomerName)
select CustomerAccount, CustomerName
from GoodsInOld 


insert into GoodsInProduct(ItemId, GoodsInId)
select o.ItemId, i.id
from GoodsInOld o
inner join GoodsIn i on o.CustomerAccount = i.CustomerAccount
                     and o.CustomerName = i.CustomerName