首页 技术 正文
技术 2022年11月9日
0 收藏 667 点赞 1,390 浏览 1340 个字

万事都是从最简单的一句“hello world”开始,所以我接下里介绍的sql触发器学习案例也从最简单的案例来说明分析:

1.首先创建表,这几张表你们也许很熟,在百度搜触发器案例都是使用这2张表

Create Table Student(              --学生表
ID int primary key identity(1,1),
StudentID int --学号
) Create Table BorrowRecord( --学生借书记录表
BorrowRecord int identity(1,1), --流水号
StudentID int , --学号
BorrowDate datetime, --借出时间
ReturnDAte Datetime, --归还时间
)

2.添加测试数据

INSERT into Student(studentID) values(1)
INSERT into Student(studentID) values(2)
INSERT into BorrowRecord(studentID,BorrowDate,ReturnDAte) VALUES(1,getdate(),getdate()+1)
INSERT into BorrowRecord(studentID,BorrowDate,ReturnDAte) VALUES(2,getdate(),getdate()+1)

3.编写一个解决如下问题的一个触发器:如果我更改了学生的学号,我希望他的借书记录仍然与这个学生相关(也就是同时更改借书记录表的学号);

  1)sql脚本:

    

create Trigger truStudent
On Student --在Student表中创建触发器
for Update --为什么事件触发
As --事件触发后所要做的事情
IF update(studentID)
BEGIN
declare @stuidnew int --从临时表Inserted记录新的的学号ID
declare @stuidold int --从临时表Deleted记录跟新以前旧的的学号ID
select @stuidold=studentID from Deleted
select @stuidnew=studentID from Inserted
update BorrowRecord set studentID=@stuidnew where studentID=@stuidold
print @stuidnew
print @stuidold
end

4.测试触发器

update  Student set  StudentID=111 where studentID=1

结果:把Student表studentID=1的一条记录修改为studentID=111,这个时候BorrowRecord表与Student对应StudengID那条记录的StudengID值也会改变(如图所示)

Sql Server触发器案例(初学者学习案例)

重点是知道触发器主要的2张表:

–触发器的操作 deleted表和inserted表的数据变化
–插入操作(Insert)Inserted表有数据,Deleted表无数据
–删除操作(Delete)
–Inserted表无数据,Deleted表有数据
–更新操作(Update)
–Inserted表有数据(新数据),Deleted表有数据(旧数据)

希望这个对初学者有帮助!

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,000
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,512
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,358
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,141
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,771
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,849