Updating foreign key values

邮差的信 提交于 2019-12-02 04:58:16

问题


I have a database application in which a group is modeled like this:

TABLE Group
(
  group_id integer primary key,
  group_owner_id integer
)

TABLE GroupItem
(
  item_id integer primary key,
  group_id integer,
  group_owner_id integer,
  Foreign Key (group_id, group_owner_id) references Group(group_id, group_owner_id)
)

We have a multi field foreign key set up including the group_owner_id because we want to ensure that a GroupItem cannot have a different owner than the Group it is in. For other reasons (I don't think I need to go into detail on this) the group_owner_id cannot be removed from the GroupItem table, so just removing it is not an option.

My big problem is if i want to update the group_owner_id for the entire group, I'm writing code like this (in pseudo code):

...
BeginTransaction();
BreakForeignKeys(group_items);
SetOwnerId(group, new_owner_id);
SaveGroup(group);
SetOwnerId(group_items, new_owner_id);
SetForeignKeys(group_items, group);
SaveGroupItems(group_items);
CommitTransaction()
...

Is there a way around doing this? It seems a bit clunky. Hopefully, I've posted enough detail.

Thanks.


回答1:


Does SQL Server not support UPDATE CASCADE? :-

Foreign Key (group_id, group_owner_id)
 references Group(group_id, group_owner_id)
 ON UPDATE CASCADE

Then you simply update the Group table's group_owner_id.




回答2:


Tony Andrew's suggestion works. For example, say you'd like to change the owner of group 1 from 2 to 5. When ON UPDATE CASCADE is enabled, this query:

update [Group] set group_owner_id = 5 where group_id = 1

will automatically update all rows in GroupItem.

If you don't control the indexes and keys in the database, you can work around this by first inserting the new group, then modifying all rows in the dependant table, and lastly deleting the original group:

insert into [Group] values (1,5)
update [GroupItem] set group_owner_id = 5 where group_id = 1
delete from [Group] where group_id = 1 and group_owner_id = 2

By the way, GROUP is a SQL keyword and cannot be a table name. But I assume your real tables have real names so this is not an issue.




回答3:


You might try to add an update rule to cascade changes.

Microsoft Links
Foreign Key Relationships Dialog Box (see Update Rule)
Grouping Changes to Related Rows with Logical Records



来源:https://stackoverflow.com/questions/1668695/updating-foreign-key-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!