ttkalec1 Posted April 18, 2008 Posted April 18, 2008 Hi, I don't understand how relationships and constraints in a database work... Actually, I just wanna know if this is possible: I have two tables: 1. contains a primary key, and the 2. contains foreign key that is linked to the first one. It looks like this: 1.table ID Name Year 2.table ID Description Is it possible to delete a record in first table (which contains primary key), and then, because of their relationship, rows in the second table containing ID (foreign key) be deleted? Or do I need to do it all programatically Btw. I'm using Microsoft SQL Server 2005 Express Quote
Diesel Posted April 19, 2008 Posted April 19, 2008 A foreign key constraint says... for every entry in the child table, an entry in the parent table must exist. You can delete child records in SQL Server 2005 using 2 different methods: 1. A trigger 2. The CASCADE option As long as you have the authority to modify the table schema, I recommend using the CASCADE option. It is faster and does not require the maintenance of maintaining a trigger. ALTER TABLE Table2 ADD CONSTRAINT fk_id FOREIGN KEY (ID) REFERENCES Table1 (ID) ON DELETE CASCADE This will delete the corresponding child record whenever you delete a parent record. Make sure this is really what you want. I would offer another tip, that you create a unique primary key for table 2. Having multiple objects in the db accessible with the same key violates a normalization rule. Quote
Nate Bross Posted May 23, 2008 Posted May 23, 2008 This will delete the corresponding child record whenever you delete a parent record. Make sure this is really what you want. If this is NOT what you want, you should have a good reason for leaving orphaned child records in your database. I would offer another tip, that you create a unique primary key for table 2. Having multiple objects in the db accessible with the same key violates a normalization rule. This is true; every table should have its own primary key, in addition to any forign keys that are needed. Quote ~Nate� ___________________________________________ Please use the [vb]/[cs] tags on posted code. Please post solutions you find somewhere else. Follow me on Twitter here.
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.