Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Get Identity of Deleted Record 1

Status
Not open for further replies.

skispray

Programmer
Feb 28, 2003
16
US
I'm trying to set an SQL trigger so that when I delete a record from one table it deletes the records in another table with the same ID as the record just deleted.

I thought this would work but it doesn't:
DELETE FROM Table2 WHERE ID=@@IDENTITY

Can anyone help? Thanks!
 
Here's an example where I delete the records from 2 related tables when a record is deleted from the orders table.
CREATE trigger dbo.tr_Delete_Record_From_OrderDetail_Shipping
on
dbo.tbl_Orders
For Delete
AS

Declare @OrderID int
select @OrderID = OrderID from Deleted
DELETE tbl_OrderDetail WHERE OrderID=@OrderID
DELETE tbl_Shipping WHERE OrderID=@OrderID
 
That code is unnecessary complicated and will not work correctly in some cases.

All you need is

Code:
DELETE from tbl_Shipping WHERE OrderID in (select OrderID from deleted)
 
swamp boogie is right, the other code only works if you delete only one record at a time, a very dangerous assumption in a trigger.
 
But Swampboogie code has to be inside the Trigger because its using the Deleted table.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top