0

我在 SQL Server 2005 数据库中有一个表,它与其他表有很多连接。每隔一段时间,基表就会出现重复条目​​,我们编写了一个存储过程,它从所有连接的表中移动数据,然后删除重复的条目。

问题是,随着项目不断增长,连接表的数量开始变得难以管理,有时开发人员忘记更新存储过程,然后合并过程就会失败。

TSQL 中是否有更平滑的合并功能?我在想,因为所有表都与foreign keys需要更新/插入的表连接,很可能仅通过读取表连接来计算。

表结构看起来像这样:

Main table
------------------------
mainid (PK) | datacolumns...

Sub table 1:
------------------------
subid1 (PK) | mainid (FK) | datacolumns...

Sub table 2:
------------------------
subid2 (PK) | mainid (FK) | datacolumns...

Sub table 3:
------------------------
subid3 (PK) | datacolumns...

Connection table between "Main table" and "Sub table 3":
------------------------
mainid (FK) | subid3 (FK)

现在我有两行,Main table其中可能有也可能没有Sub table 1和中的子条目Connection table

Sub table 1应始终使用新的mainid. Sub table 2并且具有唯一的键限制,因此只有在条目尚不存在Connection table时才应使用新的来更新它们。mainid

这是一个严重的过度简化,因为我们正在谈论 20 多个表(并且还在增长),每个表对使条目唯一的原因都有自己的限制,并且如果它们不能存在于表中,则应该/不应该复制数据到唯一键。

任何帮助表示赞赏!

4

1 回答 1

0

If I understood you correctly a ON DELETE CASCADE for necessary foreign keys will solve your problem. This way deleting an entry from the "main" table will delete entries from other tables connected through FK.

于 2012-11-22T23:00:46.170 回答