Sunday, March 11, 2012

cascading delete?

I use SQL Server 2005
I have tables tblUserData, tblUsersAndGuestbook, tblGuestbook

tblUserdata contains:
UserCode int
Username nvarchar(50)

tblUsersAndGuestbook contains:
Usercode int (FK to tblUserData)
GBEntryCode int

tblGuestbook
GBEntryCode int (FK to tblUsersAndGuestbook)
GBText text

Now...if I delete a user in tblUserData I want to also delete the entries in tblUsersAndGuestbook AND in tblGuestbook.
I've heard something about cascading delete, but how can i configure that in my database?
Or do I manually need to delete all entries from code?

Im a bit lazy and never did this in code in the last 5 years, but when you define your FK in either Visual Studio or in SQL Management Studio, in the relations properties of the tables, pick the FK, go in its properties, under Database Designer you have the option Insert and Update Specification. There, Update Rule and Delete rule can be set to cascade.

In a master -> detail (1 to N) scenario, if you delete a row from the master, all the detail is automatically deleted along with it.

Its pretty dangerous though, I prefer to avoid it and do it manually in a transaction.

|||

Peter Smith:

I use SQL Server 2005
I have tables tblUserData, tblUsersAndGuestbook, tblGuestbook

tblUserdata contains:
UserCode int
Username nvarchar(50)

tblUsersAndGuestbook contains:
Usercode int (FK to tblUserData)
GBEntryCode int

tblGuestbook
GBEntryCode int (FK to tblUsersAndGuestbook)
GBText text

Now...if I delete a user in tblUserData I want to also delete the entries in tblUsersAndGuestbook AND in tblGuestbook.
I've heard something about cascading delete, but how can i configure that in my database?
Or do I manually need to delete all entries from code?

Try these two threads of how to enable it, DRI(declarative referential integrity) is very simple if a references b then b must exist. And it has replaced most triggers for the last five years. Hope this helps.


http://forums.asp.net/thread/1315554.aspx

http://forums.asp.net/thread/1120122.aspx

No comments:

Post a Comment