2016-09-23 83 views
0

我有兩個表我希望我的代碼可以從第一個表中的每一列中插入。這裏是我的代碼:對於每一列有多個插入

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

我收到錯誤:消息2627,無法在對象'dbo.Inventory'中插入重複鍵。

+1

Your InventoryItemID列是主鍵? –

+0

沒有'id'是主鍵。我可以理解它不能運行Max(id)+1爲每個插入。 – DiH

+1

'InventoryItemID'是'primary'或'unique'鍵。這就是爲什麼它不允許你重複值。 –

回答

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

或者我是否可以將ID更改爲僅爲此插入自動增量,並在完成後禁用自動增量? ALTER TABLE table_name ALTER COLUMN column_name數據類型,類似這樣的 – DiH

+0

不知道這是否可能 – GuidoG

+0

我相信不可能將現有列更改爲標識 – GuidoG

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

接下來插入你的值到這個臨時表變量和使用id在臨時表中添加庫存表的最大ID計算要插入到表中的值。

+0

您還可以使用Inventory Table的最大ID來初始化身份 – GuidoG