I am a beginner at SQL and I don\'t know much about Transact-SQL.
I realize this is a newbie question, but I\'m looking for a simple solution.
I have a table
I think you want something like the below. The temporary table @Output will capture the inserted identities for the first table, then these can be used when inserting to the second table.
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