如何在SQL中创建2到N个关联

时间:2017-01-30 22:57:34

标签: sql sql-server

以前我的表会以一对一的方式关联记录,所以我只是将关联记录模型的ID存储在其合作伙伴记录中。

我更新了我的模型,允许这些记录与许多其他记录相关联,只要它们在多个列中具有相同的值即可。我在我的数据库中添加了一个新表,它将为每组关联记录存储唯一的分组ID。我还在模型中添加了一列,以便关联的记录可以保存对其分组ID的引用。

我在这里有两张桌子。主表我们可以称之为“记录”,然后是“recordAssociation”表。

该模型除了以外无关紧要:

记录 PK guid | {然后是一些字段,在我们的例子中是address1,address2,city,zip等}} FK RecordAssociationId guid

RecordAssociation PK guid

如何填充关联表并更新记录表。

1 个答案:

答案 0 :(得分:1)

这是我们提出的解决方案:

--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;