Click here to Skip to main content
15,921,548 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a master table with a primary key column refered to by many columns in other tables in the same database, I want to delete a row in that table without having to delete others first (which have referent values to that table). I can simply do this in Access but it seems a bit tricky in SQL Server.
Could you please guide me through the how to achieve that? I like the simplicity, I felt how it is in Access and at that time I thought that's why they provide the so-called "foreign key"!
Thank you very much!
Posted
Updated 21-Oct-11 17:50pm
v5

The whole point in making it difficult is because of referential entegrity. If you delete the row from the parent table then all rows in any other table would be ophaned and would cause problems with queries and such. Set ON DELETE CASCADE on the relationship to delete the rows in the child table as well.

http://msdn.microsoft.com/en-us/library/aa933119(v=sql.80).aspx[^]
 
Share this answer
 
Comments
Mehdi Gholam 22-Oct-11 0:26am    
It's like saying can I open a safe without the key! 5!
[no name] 22-Oct-11 2:39am    
Thank you very much!
You have helped me out!
SQL
ALTER TABLE MasterTable
ADD CONSTRAINT fk_xyz 
FOREIGN KEY (xyz) 
REFERENCES ChildTable (xyz) ON DELETE CASCADE
 
Share this answer
 
Comments
[no name] 23-Oct-11 14:05pm    
Thank you very much!
First u have to delete the record from Child table then remove from parent table .
 
Share this answer
 
Comments
[no name] 23-Oct-11 14:13pm    
Oh that's the normal way. I think you should refer to other solutions for this question of mine and feel how easy to delete the rows. I don't know what the advantage of doing that the normal way (as you suggested) is (compared to the way I was asking for), but of course it is also a way to do in some case.
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900