如果您不想更改数据库架构,可以选择INSTEAD OF TRIGGER。
触发器允许您在执行特定操作时执行任何任务。在这种情况下,您可以在父/主表上编写INSTEAD OF DELETE 触发器,在触发器内部,您可以从子表中删除相关条目。看看下面的例子。
CREATE TABLE dbo.Gestiones
(
id_gestione int IDENTITY (1, 1) PRIMARY KEY,
CUIT INT
);
CREATE TABLE dbo.ChildGestione1
(
ID INT IDENTITY PRIMARY KEY,
id_gestioneFK int REFERENCES Gestiones(id_gestione),
Description VARCHAR(100)
);
CREATE TABLE dbo.ChildGestione2
(
ID INT IDENTITY PRIMARY KEY,
id_gestioneFK int REFERENCES Gestiones(id_gestione),
Description VARCHAR(100)
);
CREATE TABLE dbo.ChildGestione3
(
ID INT IDENTITY PRIMARY KEY,
id_gestioneFK int REFERENCES Gestiones(id_gestione),
Description VARCHAR(100)
);
INSERT INTO dbo.Gestiones (CUIT)
VALUES (10), (20), (30), (40);
INSERT INTO dbo.ChildGestione1 (id_gestioneFK, Description)
VALUES (1,'abc'), (2,'efg');
INSERT INTO dbo.ChildGestione2 (id_gestioneFK, Description)
VALUES (1,'abc'), (3,'pqr');
INSERT INTO dbo.ChildGestione3 (id_gestioneFK, Description)
VALUES (1,'abc'), (3,'pqr'), (4,'stu');
GO
SELECT * FROM dbo.Gestiones
SELECT * FROM dbo.ChildGestione1
SELECT * FROM dbo.ChildGestione2
SELECT * FROM dbo.ChildGestione3
DELETE FROM Gestiones where CUIT = 10
SELECT * FROM dbo.Gestiones
SELECT * FROM dbo.ChildGestione1
SELECT * FROM dbo.ChildGestione2
SELECT * FROM dbo.ChildGestione3
CREATE TRIGGER InsteadOfDELETETriggerExample ON [Gestiones]
INSTEAD OF DELETE
AS
BEGIN
DECLARE @id_gestione INT
SELECT @id_gestione = id_gestione FROM deleted
IF @id_gestione IS NOT NULL
BEGIN
DELETE FROM ChildGestione1 WHERE id_gestioneFK = @id_gestione
DELETE FROM ChildGestione2 WHERE id_gestioneFK = @id_gestione
DELETE FROM ChildGestione3 WHERE id_gestioneFK = @id_gestione
/*...
and so on...you can right as many child tables as you have
*/
-- At the last, delete the entry from parent table
DELETE FROM Gestiones WHERE id_gestione = @id_gestione
END
PRINT 'Successfully deleted references of CUIT column from all the child tables.'
END
GO
DROP TRIGGER InsteadOfDELETETriggerExample
GO
DROP TABLE dbo.ChildGestione3;
DROP TABLE dbo.ChildGestione2;
DROP TABLE dbo.ChildGestione1;
DROP TABLE dbo.Gestiones;
以上代码仅适用于主表中的一个删除条目,如果删除操作影响父表中的多个条目,则您需要将JOINdeleted 表与您的子表一起删除。