DECLARE @tempLKP as table(personId int, childId int, SD datetime, ED datetime); INSERT INTO @tempLKP SELECT (SELECT TOP 1 Entity_Id from DT_PERSON INNER JOIN LNK_PERSON_CHECK ON Left_Join = Entity_Id AND Right_Join = o.Entity_Id ORDER BY Entity_Id DESC) AS personId, o.Entity_Id AS childId, o.Entity_Start_Date AS SD, (SELECT TOP 1 Entity_End_Date FROM DT_CHECK a WHERE a.Entity_Id = o.Entity_Id ORDER BY Entity_Start_Date DESC) AS ED FROM DT_CHECK o WHERE o.Ndx = (SELECT TOP 1 Ndx FROM DT_CHECK a WHERE a.Entity_Id = o.Entity_Id ORDER BY Entity_Start_Date ASC) DELETE FROM LNK_PERSON_CHECK INSERT INTO LNK_PERSON_CHECK SELECT * FROM @tempLKP WHERE NOT personId IS NULL DELETE FROM @tempLKP INSERT INTO @tempLKP SELECT (SELECT TOP 1 Entity_Id from DT_PERSON INNER JOIN LNK_PERSON_PASSPORT ON Left_Join = Entity_Id AND Right_Join = o.Entity_Id ORDER BY Entity_Id DESC) AS personId, o.Entity_Id AS childId, o.Entity_Start_Date AS SD, (SELECT TOP 1 Entity_End_Date FROM DT_PASSPORT a WHERE a.Entity_Id = o.Entity_Id ORDER BY Entity_Start_Date DESC) AS ED FROM DT_PASSPORT o WHERE o.Ndx = (SELECT TOP 1 Ndx FROM DT_PASSPORT a WHERE a.Entity_Id = o.Entity_Id ORDER BY Entity_Start_Date ASC) DELETE FROM LNK_PERSON_PASSPORT INSERT INTO LNK_PERSON_PASSPORT SELECT * FROM @tempLKP WHERE NOT personId IS NULL