每列有多个插入

时间:2016-09-23 12:51:08

标签: sql-server sql-server-2008

我有两个表我希望我的代码从第一个表中的每一列插入。这是我的代码:

insert into Inventory (InventoryItemID,ID) 
select 
       inventoryitemid,
      (select MAX(id)+1 from Inventory) 
from Inventory_Panel 
where InventoryItemID 
IN 
(
    select InventoryItemID 
    from InventoryBarCodes 
    WHERE BarCode IN (SELECT BarCode FROM Market)
)                     

我收到错误:Msg 2627,无法在对象'dbo.Inventory'中插入重复键。

2 个答案:

答案 0 :(得分:0)

是的,你可以在这样的循环中完成:

declare @InventoryItemID int
declare @ID int

declare crInventoryPanel Cursor local fast_forward for
  select inventoryitemid
  from Inventory_Panel 
  where InventoryItemID IN ( select InventoryItemID 
                             from InventoryBarCodes 
                             WHERE BarCode IN (SELECT BarCode FROM Market)
                           )                        
open crInventoryPanel
fetch next from crInventoryPanel into @InventoryItemID
while @@FETCH_STATUS = 0
begin
    select @ID = max(ID) + 1 from Inventory

    insert into Inventory (InventoryItemID, ID)
    values (@InventoryItemID, @ID)

    fetch next from crInventoryPanel into @InventoryItemID
end
close crInventoryPanel
deallocate crInventoryPanel

答案 1 :(得分:0)

DECLARE @tTemp TABLE(
Id int IDENTITY(1, 1)
, InventoryItemId int)

接下来将值插入此临时表变量并使用临时表中的id添加Inventory表的最大ID以计算要插入表中的值。