Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 trigger - logical problem

Author  Topic 

BigCharlie
Starting Member

2 Posts

Posted - 2009-03-03 : 15:10:05
Hi all,

I'm a newbie to SQL server (2005 Express edition) and I'm trying to get used to triggers. I've come to this problem. I've three tables:
  • company
  • address
  • company_address

First stores company details, second address details, the last one relations between companies and addresses. One company could have 0..n addresses. So far so good.

Now the problem:
- on company_address there is cascade constraint (deleted company = deleted relations with addresses)
- I would like to write trigger, that deletes address, when there are no other relations to this address

I was thinking that I could wrote "for delete" trigger on company_address. Works perfectly, when there is only one company with one address. But then I realized that there could be more than one address -> more records in virtual deleted table. And I evidently couldn't handle that with my poor knowledge. So how to wrote that trigger?

Thanks for good ideas!

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-03-03 : 15:25:02
Here's an example of a trigger that properly handles multiple rows in the trigger table: http://weblogs.sqlteam.com/tarad/archive/2004/09/14/2077.aspx

And here's a delete example:

DELETE t1
FROM Table1 t1
INNER JOIN deleted d
ON t1.PK = d.PK

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

BigCharlie
Starting Member

2 Posts

Posted - 2009-03-04 : 08:39:51
Thanks a lot, Tara, that helped me.

The problem was to find that correct subquery in DELETE trigger. As usual.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-03-04 : 12:06:18
You're welcome.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -