I am looking for a set based T-SQL solution to insert data into a parent table and related data in another table at the same time. The problem is not knowing the primary key values to link the data in related table. Below is a simplified version of what I'm trying to do. The temp table represents data gathered from a query from other tables in the database. The code values are not unique.I have searched high and low for a solution but have not found anything. Any help is appreciated.CREATE TABLE Parent( ID INT IDENTITY(1,1), Code1 CHAR(1), CONSTRAINT PK_Parent_ID PRIMARY KEY (ID))CREATE TABLE Related( ID INT IDENTITY(1,1), ParentID INT, Code2 CHAR(2), CONSTRAINT PK_Related_ID PRIMARY KEY (ID), CONSTRAINT FK_Related_ParentID FOREIGN KEY(ParentID) REFERENCES Parent (ID))CREATE TABLE #TmpOther( Code1 CHAR(1), Code2 CHAR(2))INSERT #TmpOther VALUES('A','A1')INSERT #TmpOther VALUES('D','D2')INSERT #TmpOther VALUES('J','J2')INSERT #TmpOther VALUES('F','F3')INSERT Parent SELECT Code1 FROM #TmpOtherSELECT * FROM Parent-- Set based INSERT for table Related??DROP TABLE #TmpOtherDROP TABLE RelatedDROP TABLE Parentinsert into related(ParentId,Code2)Select Parent.Id, Code2 from Parent, #TmpOther where Parent.Code1 = #TmpOther.Code1/* data for table ParentID Code11 A2 D3 J4 FDesired data for table RelatedID ParentID Code21 1 A12 2 D23 3 J24 4 F3*/