请教一个简单的触发器编写
tbA表中字段A1,B1 其中B1为INT型
tbB表中字段C1,D1 其中D1为INT型
要求
1、当tbB中插入一条新记录时,将满足条件tbA.A1=tbB.C1的记录的tbA.B1值更新,更新为tbA.B1=tbA.B1-tbB.D1
2、当tbB中的原有记录的D1值改变时,将满足条件tbA.A1=tbB.C1的记录的tbA.B1值更新,更新为tbA.B1=tbA.B1-(新tbB.D1-原tbB.D1)
希望那位高手能帮忙解决一下!
------解决方案--------------------CREATE TABLE tbA
(
A1 VARCHAR(20),
B1 INT
)
CREATE TABLE tbB
(
ID INT IDENTITY(1,1), --这里加这个是为了防止重复
C1 VARCHAR(20),
D1 INT
)
INSERT INTO tbA
SELECT 'A',20 UNION ALL
SELECT 'B',30 UNION ALL
SELECT 'C',40
GO
CREATE TRIGGER TR_TB
ON tbB
FOR INSERT,UPDATE
AS
BEGIN
IF EXISTS ( SELECT * FROM DELETED A WHERE EXISTS ( SELECT * FROM INSERTED B WHERE A.id = B.id ))
BEGIN
UPDATE A SET B1 = A.B1 - (B.D1-C.D1)
FROM tbA A,INSERTED B,DELETED C WHERE A.A1 = B.C1 AND B.ID = C.ID
END
ELSE
UPDATE A SET B1 = A.B1 - B.D1
FROM tbA A, INSERTED B WHERE A.A1 = B.C1
END
GO
SELECT * FROM tbA
insert into tbB VALUES ('B',10)
SELECT * FROM tbA
UPDATE tbB SET D1 = 15 WHERE ID = 1
SELECT * FROM tbA
DROP TRIGGER TR_TB
DROP TABLE tbA
DROP TABLE tbB
A1 B1
-------------------- -----------
A 20
B 30
C 40
(所影响的行数为 3 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
A1 B1
-------------------- -----------
A 20
B 20
C 40
(所影响的行数为 3 行)
(所影响的行数为 1 行)
(所影响的行数为 1 行)
A1 B1
-------------------- -----------
A 20
B 15
C 40
(所影响的行数为 3 行)