各位帮我写个触发器的例子?

mjjzg 2008-09-21 09:19:53
由于长时间不在数据库这方面研究了,在编程时最常用的也就存储过程,而如今想温故一下触发器,可却给忘了怎么用,网上也找了些例子,但都太笼统了,各位给我写个触发器的例子,并简要说明一下,让我回顾一下...
...全文
90 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
hyde100 2008-09-22
  • 打赏
  • 举报
回复

create trigger my_insert on tableName
for insert
as
****
--------------------------------------
create trigger my_update on tableName
for update
as
****
--------------------------------------
create trigger my_delete on tableName
for delete
as
****

hsie168518 2008-09-22
  • 打赏
  • 举报
回复
CREATE TABLE [t_xwx_tb001] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[FG] [char] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[amount] [decimal](18, 2) NULL
) ON [PRIMARY]
GO


CREATE TABLE [t_xwx_tb002] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[fg] [char] (10) COLLATE Chinese_PRC_CI_AS NULL ,
[SumT] [decimal](18, 2) NULL
) ON [PRIMARY]
GO


INSERT INTO [t_xwx_tb001]([FG], [amount])VALUES('08/3301',120.50)
INSERT INTO [t_xwx_tb001]([FG], [amount])VALUES('08/3301',50)
INSERT INTO [t_xwx_tb001]([FG], [amount])VALUES('08/3301',30)
INSERT INTO [t_xwx_tb001]([FG], [amount])VALUES('08/3302',1000)
INSERT INTO [t_xwx_tb001]([FG], [amount])VALUES('08/3302',500)
INSERT INTO [t_xwx_tb001]([FG], [amount])VALUES('08/3302',100)

INSERT INTO [t_xwx_tb001]([FG], [SumT])VALUES('08/3301',200.50)
INSERT INTO [t_xwx_tb001]([FG], [SumT])VALUES('08/3302',1500)
INSERT INTO [t_xwx_tb001]([FG], [SumT])VALUES('08/3303',100)



如上,表2 是表1的根据FG求总和。
现在操作表1,
增加数据后表2 SumT会自动加上。
删除数据后表2 SumT会自动减去。
更新数据后表2 也会自动更新。

我写了3个简单的触发器(因为一起写难度比较大)

1:
create trigger tri_up on t_xwx_tb001 for update
as

if update(amount)

begin
update t_xwx_tb002 set Sumt=sumt+c.amount-cc.amount from inserted c ,deleted cc
where t_xwx_tb002.FG=c.fg and cc.fg=t_xwx_tb002.fg
end


2:
create trigger tri_in on t_xwx_tb001 for insert
as

update t_xwx_tb002 set Sumt=sumt+c.amount from inserted c
where t_xwx_tb002.FG=c.fg

3:

create trigger tri_de on t_xwx_tb001 for delete
as

update t_xwx_tb002 set Sumt=sumt-cc.amount from deleted cc
where t_xwx_tb002.FG=cc.fg
wzy_love_sly 2008-09-21
  • 打赏
  • 举报
回复
up
Andy-W 2008-09-21
  • 打赏
  • 举报
回复
帮助文档
水族杰纶 2008-09-21
  • 打赏
  • 举报
回复
create trigger T_Text
on table
for insert
as
sql语句~
fcuandy 2008-09-21
  • 打赏
  • 举报
回复
create trigger t
on ta
for insert
as
insert tb select * from inserted

在 ta 上建立触发器 t,当向 ta insert记录时,同时把记录插入到 tb

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧