这是我们提出的解决方案:
--Start by setting up a temp table so we can do joins
declare @recordAssociationTemp table
(
UniqueId VARCHAR(500) NOT NULL,
NewAssociationId uniqueidentifier NULL,
CreatedBy uniqueidentifier NOT NULL
);
--Select the columns we want to associate on by making a unique ID out of the common fields
with temp as
(
select isnull(AddressLineOne, '') + isnull(AddressLineTwo, '') + isnull(AddressCity, '') + isnull(AddressState, '') + isnull(AddressZip,'')+ isnull(a.CreatedBy,'') as UniqueId,
a.CreatedBy,
ROW_NUMBER() over (partition by isnull(AddressLineOne, '') + isnull(AddressLineTwo, '') + isnull(AddressCity, '') + isnull(AddressState, '') + isnull(AddressZip,'')
+ isnull(a.CreatedBy,'') order by a.CreatedBy) as RowNum
from dbo.[Record] as a inner join DGSystem as dgs on a.SystemId = dgs.Id
)
--ROW_NUMBER() helps us assign an increasing ID to each duplicate row so we can avoid making associations for records that only have a single entry
insert @recordAssociationTemp (UniqueId, CreatedBy)
select distinct UniqueId, CreatedBy
from temp
where RowNum > 1; -- > 1 allows us to skip over records that don't have any associations
update @recordAssociationTemp
set NewAssociationId = NEWID();
--this is where we add new records to our association table with the generated unique IDs and some accociated audit data
insert into dbo.RecordAssociation
(Id, CreatedBy, CreatedDateTime, ModifiedBy, ModifiedDateTime)
select NewAssociationId, CreatedBy, SYSDATETIME(), CreatedBy, SYSDATETIME()
from @recordAssociationTemp;
--finally, we join our temp table to apply our new IDs to the record table
update a
set a.RecordAssociationId = aat.NewAssociationId
from dbo.[Record] as a inner join DGSystem as dgs on a.SystemId = dgs.Id
inner join @recordAssociationTemp as aat on isnull(AddressLineOne, '') + isnull(AddressLineTwo, '') + isnull(AddressCity, '') + isnull(AddressState, '') + isnull(AddressZip,'')
+ isnull(a.CreatedBy,'') = aat.UniqueId;