declare @ld as table
(
	DocID int,
	DocRank int
)
insert into @ld
select DOCid, dense_rank() OVER(ORDER BY DOCCONTENT) AS DocRank
 from documents
 where libtitle != ''
 
 declare @mld as table
(
	DocRank int primary key,
	MinDocID int
)
insert into @mld
select DocRank, min(DocID) MinDocID from @ld Group by DocRank

declare @trans as table
(
	DocID int primary key,
	MinDocID int
)
Insert into @Trans
Select DocID,MinDocID from @ld ld
Join @mld mld on mld.docrank = ld.docrank
where MinDocID != DocID
order by ld.DocRank
Update EE set DocID = MinDocID from entries EE
Join @trans TT on EE.DocID = TT.DocID

Delete from Documents where DocID Not in (Select DocID From Entries)