Jeg tror, du vil have noget som nedenstående. Den midlertidige tabel @Output vil fange de indsatte identiteter for den første tabel, så disse kan bruges ved indsættelse i den anden tabel.
DECLARE @Output TABLE
( FirstTableID INT NOT NULL PRIMARY KEY,
WarehouseCode VARCHAR(3),
CustomerCode VARCHAR(4)
)
INSERT INTO FirstTable (WarehouseCode, CustomerCode)
OUTPUT inserted.FirstTblID, inserted.WarehouseCode, inserted.CustomerCode INTO @Output
SELECT DISTINCT LEFT(LocationCode, 3) [WarehouseCode], CustomerCode
FROM [PrimaryTable]
INSERT INTO SecondTable (ItemCode, LocationCode, CustomerCode, FirstTblID)
SELECT p.ItemCode,
p.LocationCode,
p.CustomerCode,
o.FirstTableID
FROM [PrimaryTable] p
INNER JOIN @Output o
ON LEFT(LocationCode, 3) = WarehouseCode
AND p.CustomerCode = o.CustomerCode