首页 > 开发 > 综合 > 正文

触发器学习

2024-07-21 02:50:12
字体:
来源:转载
供稿:网友
触发器学习

数据库表:

创建语句:

--table1

CREATE TABLE [dbo].[table1]( [id] [int] IDENTITY(1,1) NOT NULL, [value] [varchar](10) NULL, CONSTRAINT [PK_table] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]

--table2

CREATE TABLE [dbo].[table2]( [id] [int] IDENTITY(1,1) NOT NULL, [count] [int] NOT NULL, CONSTRAINT [PK_table2] PRIMARY KEY CLUSTERED ( [id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY]

insert into table2(count) values(0)

--触发器语句,对table1进行插入或者删除操作会触发触发器更新table1的行数

CREATE TRIGGER insert_table1 ON table1

FOR INSERT , DELETE

AS BEGIN

UPDATE table2 set count=(SELECT count(*) FROM table1) WHERE id=1;

END; ===============================================================================================================================================

触发器知识:

一般格式:

CREATE TRIGGER <触发器名>

{BEFORE | AFTER} <触发事件> ON <表名>

FOR EACH {ROW | STATEMENT}

[WHEN <触发条件>]

<触发动作体>

触发事件:可以是INSERT、DELETE或UODATE,也可以是几个事件的组合。

触发器类型:可以分为行级触发器(FOR EACH ROW)和语句级触发器(FOR EACH STATEMENT)


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表