我正在参加「掘金·启航计划」
在本篇文章中,主要来讲讲数据库中的触发器功能
在实际项目中,触发器多数用到在数据添加、修改、删除时,额外去做的一些操作,比如:数据删除了,会通过触发器将删除数据备份到另一个表,再或者文章被阅读,通过触发器更新阅读数量
- 主要知识点列表 | 编号 | 语言或插件 | 知识点 | 说明 | | --- | --- | --- | --- | | 1 | sql server | create table | 关键词,创建表 | | 2 | sql server | indentity | 自增长函数 | | 3 | sql server | primary key | 设置主键标识 | | 4 | sql server | drop table | 移除对象,比如:表、存储过程、触发器等 | | 5 | sql server | delete tableName | 删除表记录 | | 6 | sql server | truncate tableName | 删除表所有记录,并重置自增编号重新开始 | | 7 | sql server | create trigger | 创建触发器关键词 |
【什么是触发器】
1)对于数据库而言,触发器是一种特殊存储过程
2)它不需要用户直接调用
3)当对表进行添加、更新、删除操作时,会自动触发执行
4)通过触发器操作,可以最大化确保数据的完整性和约束性,具有数据修正功能
5)它不允许主动被调用,也不允许带参数
6)一般有三种类型,insert触发器,update触发器,以及delete触发器
7)触发器是相对于表而言,可同时触发多个动作
【假设实现场景】
模拟文章被阅读,文章表记录进行更新时间操作,在文章表记录被更新时,文章阅读记录表添加一条记录
【创建表】
由上面假设场景,可创建如下几张表
1)文章表
-
表设计 编号、文章标题、文章内容、作者、阅读数量、添加时间、更新时间
-
sql语句创建表
--drop table myArticle
create table myArticle
(
id int identity(1,1) primary key,
title nvarchar(100),
content nvarchar(100),
author nvarchar(30),
readCount int,
createTime datetime,
updateTime datetime
)
- 模拟数据
insert into myArticle(title,content,author,readCount,createTime,updateTime)
values(
'触发器的使用',
'通过触发器来实现文章阅读阅读数量的统计',
'全栈小5',
0,
getdate(),
getdate()
)
- 查询记录
2)创建文章阅读记录表
为什么要多一个文章阅读记录表,这个是为了后续通过服务或者其他定时器进行阅读数量校正使用,因为在高并发下可能会存在数量更新差异
-
表设计 编号、文章编号、添加时间
-
创建表
--drop table readRecord
create table readRecord
(
id int identity(1,1) primary key,
articleId int,
createTime datetime,
)
【创建触发器】
1)关键词,create trigger
2)语句如下
--drop trigger article_tri
create trigger article_tri
on readRecord
after insert
as
begin
declare @articelId int
select @articelId=a.articleId from inserted a
declare @count int
select @count=count(a.articleId) from readRecord a where articleId=@articelId
update myArticle
set readCount=@count
where id=@articelId
end
3)添加阅读记录,查询效果
insert into readRecord(articleId,createTime)
values(1,getdate())