Answer the question
In order to leave comments, you need to log in
How to delete records in related tables using triggers in ms sql server?
Hello.
There were questions when working with the database. There are three related tables in the database, they are visible in the ER diagram.
I want that when an entry in the s_test table is deleted, the information associated with it in the test_task and s_task tables is deleted. For this I use triggers.
When an entry in s_test is deleted, the following trigger fires:
ALTER TRIGGER [dbo].[t_del_test]
ON [dbo].[s_test] INSTEAD OF DELETE
AS
DECLARE @id int;
SELECT @id = id_test from deleted;
DELETE FROM test_task WHERE id_test = @id;
DELETE FROM s_test WHERE [email protected];
ALTER TRIGGER [dbo].[t_del_test_task]
ON [dbo].[test_task] AFTER DELETE
AS
DECLARE @id int;
SELECT @id = id_task from deleted;
DELETE FROM s_task WHERE [email protected];
Answer the question
In order to leave comments, you need to log in
Here we love all sorts of perversions ...
Have you heard about cascade deletion?
Example:
ALTER TABLE [dbo].[OrderGoods] WITH CHECK ADD CONSTRAINT [FK_OrderGoods_OrderHeader] FOREIGN KEY([OrderHeaderGUID])
REFERENCES [dbo].[OrderHeader] ([GUID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[OrderGoods] CHECK CONSTRAINT [FK_OrderGoods_OrderHeader]
GO
The easiest way to develop and maintain is to write a stored procedure that cleans up your tables sequentially.
The fastest, in terms of performance, is to put the isDeleted flag on the required entity instead of deleting it, and then, during periods of low load on the database, manually clean it up by deleting records by this flag.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question