关于SQLServer 触发器的基础问题
有三张无关联的表,都有一个相同的字段,三张表分别称为表1,表2,表3,
现在想要实现在删除表1对应该字段的某行数据后,删除表2,表3对应该字段的行。
这个触发器应该怎么写。菜鸟求教。
[解决办法]
IF OBJECT_ID('T_CSDN_ONE') IS NOT NULL
BEGIN
DROP TABLE dbo.T_CSDN_ONE;
END
GO
CREATE TABLE T_CSDN_ONE
(
ID INT IDENTITY(1,1) PRIMARY KEY,
[NAME] VARCHAR(50),
NUMBER INT
)
INSERT INTO dbo.T_CSDN_ONE
SELECT 'A',20
UNION ALL
SELECT 'B',20
UNION ALL
SELECT 'A',10
UNION ALL
SELECT 'A',5
UNION ALL
SELECT 'B',40
UNION ALL
SELECT 'B',10
SELECT * FROM dbo.T_CSDN_ONE
IF OBJECT_ID('T_CSDN_TWO') IS NOT NULL
BEGIN
DROP TABLE dbo.T_CSDN_TWO;
END
GO
CREATE TABLE T_CSDN_TWO
(
[NAME] VARCHAR(50),
[SUMNUMBER] INT
)
INSERT INTO T_CSDN_TWO
SELECT 'A',35
UNION ALL
SELECT 'B',70
GO
CREATE TRIGGER TR_DELETE
ON T_CSDN_ONE
AFTER DELETE
AS
BEGIN
UPDATE T_CSDN_TWO SET SUMNUMBER=SUMNUMBER-(SELECT ISNULL(SUM(NUMBER),0) FROM DELETED WHERE NAME=T_CSDN_TWO.NAME)
END
DELETE T_CSDN_ONE WHERE ID IN (4,3,5)
SELECT * FROM dbo.T_CSDN_ONE
SELECT * FROM dbo.T_CSDN_TWO