How to delete from three tables using foreign keys?

I want to be able to select groupID and perform cascading deletion through three tables that are in the MS SQL server database. The tables are as follows:

table 1 - GROUP
-------------------------------------------
groupID | description | etc


table 2 - MEMBER
-------------------------------------------
memberID | name | etc


table 3 - MAPPINGTABLE 
-------------------------------------------
mappingID | groupID | memberID

I think that since I know the groupID, I could probably select the memberID from the mapping table based on the groupID and remove those from the member table, but usually I get the error:

"The DELETE operation is contrary to the REFERENCE constraint ... [FK constraint in the table]."

Can anybody give me some recommendations on the best way to remove these tables from all three at the same time?

Thank.

+3
5

. , - . .

Member Group, , , MappingTable.

, MappingTable Member Group. , .

, ON DELETE CASCADE, . .

MappingTable, (Member, Group)

, :

  • ( , ), .
  • , .
  • /SME, , , .
+5

, , 3, 1.

+3

, . "ON DELETE CASCADE" - , .

.

CREATE TABLE table_child
(
fieldkeyparent int,
field1 INT,
FOREIGN KEY ([fieldkeyparent]) REFERENCES Table_parent
ON DELETE CASCADE)

SQL Server.

+1

- SQL. ?

, . :

ALTER TABLE MAPPINGTABLE ADD CONSTRAINT FK_GROUPID
    FOREIGN KEY (groupID) REFERENCES GROUP(groupID)
ON DELETE CASCADE
;
0

, , ON DELETE CASCADE

ALTER TABLE mappingtable ADD CONSTRAINT fk_group_id FOREIGN KEY(groupID) REFERENCES group(groupID) ON DELETE CASCADE

ON UPDATE CASCADE, , .

What does this is when you remove the parent from GROUP, it automatically removes any link to it in the tableMAPPINGTABLE

To remove users, you will need to make a second delete statement.

0
source

Source: https://habr.com/ru/post/1735051/


All Articles