
	DECLARE @LinkTable varchar(255)
	DECLARE @LeftTable varchar(255)
	DECLARE @RightTable varchar(255)

	DECLARE TableCursor CURSOR FOR 
	SELECT RLT.Table_Name, RLT.Left_Table, RLT.Right_Table
	FROM REF_LINK_TABLES RLT
	WHERE RLT.Enabled = 1 and RLT.ReadOnly = 0
	 --get right link based on customisations
	AND RLT.CustomisationID = (SELECT Max(RLT2.CustomisationID) FROM REF_LINK_TABLES RLT2 
								INNER JOIN REF_CUSTOMISATIONS rc 
								ON RLT2.CustomisationID = rc.CustomisationID 
								AND rc.Enabled = 1 
								WHERE RLT2.Table_Name = RLT.Table_Name)
	ORDER BY RLT.Table_Name

	OPEN TableCursor;

	FETCH NEXT FROM TableCursor 
	INTO @LinkTable,@LeftTable,@RightTable;

	WHILE @@FETCH_STATUS = 0
	BEGIN

		DECLARE @execsql nvarchar(2000)
		DECLARE @Msg nvarchar(2047);

		SET @execsql = 'UPDATE ' + @LinkTable + '
		SET End_Date = 
			(SELECT CASE WHEN b.MinDate = ''31 dec 2499'' THEN NULL ELSE MinDate END
				FROM (SELECT MIN(a.Entity_End_Date) AS MinDate
					FROM 
							(SELECT TOP 1 ISNULL(Entity_End_Date, ''31 dec 2499'') AS Entity_End_Date
							FROM ' + @LeftTable + ' WHERE Entity_Id = ' + @LinkTable + '.Left_Join 
							ORDER BY Entity_Start_Date DESC
							UNION
							SELECT TOP 1 ISNULL(Entity_End_Date, ''31 dec 2499'') 
							FROM ' + @RightTable + ' WHERE Entity_Id = ' + @LinkTable + '.Right_Join 
							ORDER BY Entity_Start_Date DESC) a) b
				)
			WHERE ISNULL(End_Date, ''31 dec 2499'') <> 
				(SELECT MIN(a.Entity_End_Date) AS MinDate
						FROM 
							(SELECT TOP 1 ISNULL(Entity_End_Date, ''31 dec 2499'') AS Entity_End_Date
							FROM ' + @LeftTable + ' WHERE Entity_Id = ' + @LinkTable + '.Left_Join 
							ORDER BY Entity_Start_Date DESC
							UNION
							SELECT TOP 1 ISNULL(Entity_End_Date, ''31 dec 2499'') 
							FROM ' + @RightTable + ' WHERE Entity_Id = ' + @LinkTable + '.Right_Join 
							ORDER BY Entity_Start_Date DESC) a
				)'

			EXEC sp_executesql @execsql

			SET @execsql = 'DELETE FROM ' + @LinkTable + ' WHERE Left_Join = 0 OR Right_Join = 0'
			EXEC sp_executesql @execsql

		FETCH NEXT FROM TableCursor 
		INTO @LinkTable,@LeftTable,@RightTable;

	END

	CLOSE TableCursor;
	DEALLOCATE TableCursor;
