Delete data is constrained when there is a primary foreign key relationship between tables, add, delete fails
Solution, we can first set the check of the primary foreign key relationship to shut down → then delete the data → then open the constraint
Query the statement that turns off all foreign key constraints
SELECT 'ALTER TABLE' +O.name+ 'NOCHECK CONSTRAINT [' +F.name+ '];' asCOMMAND fromSYS. Foreign_keys FINNER JOINSYS. All_objects O onf.parent_object_id=O.object_id WHEREO.type= 'U' andF.type= 'F';
Query the statement that opens all foreign key constraints, the difference from the above is to change the NOCHECK to CHECK
SELECT 'ALTER TABLE' +O.name+ 'CHECK CONSTRAINT [' +F.name+ '];' asCOMMAND fromSYS. Foreign_keys FINNER JOINSYS. All_objects O onf.parent_object_id=O.object_id WHEREO.type= 'U' andF.type= 'F';
Adding, deleting data when SQL Server has a primary foreign key relationship