Sh M
asked on
sql 2005 cascading delete in trigger
Hi,
I need to do a cascade delete of parent table (supplier table)
I do not want to set on delete cascade on foreign key of child table.
I wrote a trigger this way but it does not work. how can I get it work:
CREATE TRIGGER amr_ValidateSupplierDelete
ON Supplier
Instead Of DELETE
AS
DECLARE @sdate datetime
SET @sdate = (SELECT sdate FROM deleted)
If (@sdate <= '2011-10-10')
BEGIN
--RAISERROR ('Record can not be deleted.',16,10)
ROLLBACK TRANSACTION
RETURN
END
ELSE
BEGIN
DECLARE @Supplier_id INT
SET @Supplier_id = (SELECT Supplier_id FROM deleted)
IF EXISTS (SELECT * FROM product WHERE Supplier_ID = @Supplier_id)
BEGIN
DELETE FROM product
FROM product s
INNER JOIN Supplier p ON s.Supplier_id = p.Supplier_id
WHERE s.Supplier_ID = @Supplier_id
END
IF EXISTS (SELECT * FROM supplier WHERE supplier _ID = @supplier _id)
BEGIN
DELETE FROM supplier WHERE supplier _ID = @supplier _id
END
COMMIT
END
the else section does not go through all queries and just does one at the time, like deletes the product but does not delete supplier....how can I get it work?
Thanks in advance
I need to do a cascade delete of parent table (supplier table)
I do not want to set on delete cascade on foreign key of child table.
I wrote a trigger this way but it does not work. how can I get it work:
CREATE TRIGGER amr_ValidateSupplierDelete
ON Supplier
Instead Of DELETE
AS
DECLARE @sdate datetime
SET @sdate = (SELECT sdate FROM deleted)
If (@sdate <= '2011-10-10')
BEGIN
--RAISERROR ('Record can not be deleted.',16,10)
ROLLBACK TRANSACTION
RETURN
END
ELSE
BEGIN
DECLARE @Supplier_id INT
SET @Supplier_id = (SELECT Supplier_id FROM deleted)
IF EXISTS (SELECT * FROM product WHERE Supplier_ID = @Supplier_id)
BEGIN
DELETE FROM product
FROM product s
INNER JOIN Supplier p ON s.Supplier_id = p.Supplier_id
WHERE s.Supplier_ID = @Supplier_id
END
IF EXISTS (SELECT * FROM supplier WHERE supplier _ID = @supplier _id)
BEGIN
DELETE FROM supplier WHERE supplier _ID = @supplier _id
END
COMMIT
END
the else section does not go through all queries and just does one at the time, like deletes the product but does not delete supplier....how can I get it work?
Thanks in advance
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER