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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 help with trigger to delete records

Author  Topic 

mlad0921
Starting Member

2 Posts

Posted - 2010-08-12 : 16:14:06
I have two tables and want to fire a trigger when records are deleted. Instead of trying to figure it out myself, I thought I'd come here first.

I have a column in each table that relates to each other.

Tbl_1.Col
Tbl_2.Col

After a record gets deleted from Tbl_1, I want to look in Tbl_2 for any records (Tbl_2.Col) that exist that do not exist in Tbl_1. Basically, I am trying to clean up Tbl_2 automatically. If Tbl_1 no longer has records in Tbl_1.Col that Tbl_2.Col has, Tbl_2 should delete its records as well. I only want this to occur after all the Tbl_1.Col records are gone.

I hope I did ok trying to explain my situation. If I need to do this in code I can, but I'd rather do it on the sql side to keep my code lighter.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-08-12 : 16:15:40
You should do this delete by using a cascading foreign key. A trigger can also be used, however the foreign key is preferred.

Is their a foreign key between these two tables on that column?

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

Subscribe to my blog
Go to Top of Page

mlad0921
Starting Member

2 Posts

Posted - 2010-08-12 : 17:42:04
The reason why I don't believe I can use a foreign key is because neither of those columns are unique. Each table can have identical entries in those columns.
Go to Top of Page

gautham09
Starting Member

2 Posts

Posted - 2010-08-12 : 18:10:41
CREATE TRIGGER del_pk
ON pk
AFTER DELETE
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;


DELETE FROM PK1 WHERE NO IN (SELECT NO FROM DELETED I)





END
GO

Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-08-12 : 22:42:39
It'd be better to use a join:

DELETE t
FROM Table2 t
JOIN deleted d
ON t.c1 = d.c1


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 -