Saya pikir Anda menginginkan sesuatu seperti di bawah ini. Tabel sementara @Output akan menangkap identitas yang disisipkan untuk tabel pertama, kemudian ini dapat digunakan saat menyisipkan ke tabel kedua.
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