I am confused about what means the update and delete rule in SQL Server 2008 Management Studio when we define foreign key constraints. I also did not find related help documents (e.g. F1 help).
Here is the screen snapshot. Appreciate if anyone could describe what do they mean and recommend some related documents to read. :-)
After creating and populating a table in SQL, the UPDATE command can be used to change the value of a column. If there is no WHERE , it will change the value of all the rows in the table, so make sure you restrict what it updates with a correct WHERE condition. The DELETE command can be used to delete rows.
The delete rule works as follows: With RESTRICT or NO ACTION, an error occurs and no rows are deleted. With CASCADE, the delete operation is propagated to the dependents of p in table D. With SET NULL, each nullable column of the foreign key of each dependent of p in table D is set to null.
What is a foreign key with "Set NULL on delete" in SQL Server? A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to NULL.
Login to the SQL Server using SQL Server Management Studio, Navigate to the Keys folder in the child table. Right click on the Keys folder and select New Foreign Key. Edit table and columns specification by clicking … as shown in the below image. Select the parent table and the primary key column in the parent table.
The foreign key defines a parent - child relationship between two tables. The primary key in the parent table is the foreign key in the up to n child table rows.
Now if that primary key in the parent table gets UPDATE, the UPDATE RULE kicks in. Either all the child rows are also updated, set to NULL or whatever. Best practice however is to have a primary key that NEVER changes (a fixed ID or something), so that's the less important rule.
The more important one is the DELETE rule - what if the parent row is deleted (e.g. the Order is deleted)? You can either also delete all child rows (all the Order line items) with CASCADE DELETE, or you can set their foreign key to NULL (they don't have a parent anymore) - that's totally up to your concrete scenario.
In the Order/order lines scenario, it might be totally useful to delete the order lines when the complete order gets deleted, but you probably don't want to delete a product, just because an order that references it has been deleted - there's no one single CORRECT answer - it depends on your scenario and your app.
Marc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With