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 2005 Forums
 Other SQL Server Topics (2005)
 how to write a delete trigger in sql server 2005

Author  Topic 

sql2010
Starting Member

6 Posts

Posted - 2010-04-06 : 14:44:33
how to write a delete trigger in sql server? Is this the right syntax/way to write a trigger that would delete the rows in the tableB for any deletes on the tableA based on the foreign key.

CREATE TRIGGER trig_del_encounters

ON tableA

FOR DELETE

AS

BEGIN

DELETE from tableB where tableB.foreignkey= tableA.foreignkey

END

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-06 : 15:20:13
You have to reference the "deleted" trigger table in order to know which rows to delete. That table is what contains the rows.

DELETE B
FROM tableB B
JOIN tableA A
ON A.ColumnZ = B.ColumnZ
JOIN deleted D
ON A.ColumnZ = D.ColumnZ

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

Subscribe to my blog
Go to Top of Page

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2010-04-06 : 16:48:29
In fact you can remove one of the joins too

DELETE B
FROM tableB B
--JOIN tableA A
--ON A.ColumnZ = B.ColumnZ
JOIN deleted D
ON B.ColumnZ = D.ColumnZ
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-06 : 17:07:57
Yeah that's true! D'oh!

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

Subscribe to my blog
Go to Top of Page

sql2010
Starting Member

6 Posts

Posted - 2010-04-12 : 11:14:38
Thanks so much for your replies!!

Is this the right trigger syntax??

CREATE TRIGGER trig_del_encounters

ON tableA

FOR DELETE

AS

BEGIN

DELETE *
FROM tableB
JOIN deleted d
ON b.foreignkey = d.foreignkey
END

Go to Top of Page

sql2010
Starting Member

6 Posts

Posted - 2010-04-12 : 11:26:09
I keep getting a syntax error when just trying to execute this trigger.
Go to Top of Page

sql2010
Starting Member

6 Posts

Posted - 2010-04-12 : 11:35:27
This is the trigger that I am trying to execute:

Any help is very much appreciated. Thanks in advance.

CREATE TRIGGER test_trig

ON dbo.Table_1

FOR DELETE

AS
BEGIN
delete from dbo.Table_2 a
JOIN
deleted d
ON a.joincol = d.joincol

END
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-04-12 : 18:01:57
DELETE a
FROM Table_2 a
...

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 -