sql server 2005 update 触发器

A表:主键自动增长列AID,money;B表:主键自动增长列BID,money求:A表的money增加和和减少,b表的money插入增加或减少的金钱额... A表:主键自动增长列AID,money;
B表:主键自动增长列BID,money
求:
A表的money增加和和减少,b表的money 插入增加或减少的金钱额
展开
 我来答
wangzhiqing999
2011-03-22 · TA获得超过1.6万个赞
知道大有可为答主
回答量:7048
采纳率:100%
帮助的人:3330万
展开全部
CREATE TABLE A(
AID INT IDENTITY(1, 1) PRIMARY KEY,
money INT
);

CREATE TABLE B(
BID INT IDENTITY(1, 1) PRIMARY KEY,
money INT
);
go

CREATE TRIGGER AfterUpdateA
ON A
FOR INSERT,UPDATE,DELETE
AS
BEGIN

IF EXISTS(SELECT 1 FROM inserted) AND NOT EXISTS(SELECT 1 FROM deleted)
BEGIN
-- 插入触发.
INSERT INTO B
SELECT
inserted.money
FROM
inserted;
END;

IF EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
BEGIN
-- 更新触发.
INSERT INTO B
SELECT
inserted.money - deleted.money
FROM
inserted, deleted
WHERE
inserted.AID = deleted.AID;
END;

IF NOT EXISTS(SELECT 1 FROM inserted) AND EXISTS(SELECT 1 FROM deleted)
BEGIN
-- 删除触发
INSERT INTO B
SELECT
0 - deleted.money
FROM
deleted;
END;
END;
go

-- 一条SQL语句,插入一条数据
INSERT INTO A VALUES (100);

-- 一条SQL语句,插入多条数据
INSERT INTO A
SELECT 10
UNION ALL SELECT 20;
GO

-- 一条SQL语句,更新一条数据
UPDATE A SET money = money - 50 WHERE AID = 1;

-- 一条SQL语句,更新多条数据
UPDATE A SET money = money + 50 WHERE AID != 1;
GO

-- 一条SQL语句,删除一条数据
DELETE FROM A WHERE AID = 1;

-- 一条SQL语句,删除多条数据
DELETE FROM A WHERE AID != 1;
GO

1> SELECT * FROM B
2> GO
BID money
----------- -----------
1 100
2 20
3 10
4 -50
5 50
6 50
7 -50
8 -70
9 -60

(9 行受影响)
liaojielin
2011-03-23 · TA获得超过161个赞
知道答主
回答量:197
采纳率:0%
帮助的人:189万
展开全部
CREATE TRIGGER [B] ON [dbo].[A]
FOR update
AS
begin
insert B as B set (select money as A from A where A.AID = inserted) values (B.money)
end
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式