sqlserver 触发器示例

本文详细介绍并演示了SQL触发器的创建与使用,包括用户登录日志记录、用户信息修改日志记录、员工新入职自动创建工资记录及更新员工奖金等场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码如下:

1 --检查当前触发器是否已存在
2 IF exists(SELECT * FROM sysobjects WHERE xtype='TR' AND [name]='TR_INSERTUserInfo_LoginLog')
3 --存在即删除该触发器
4 DROP TRIGGER TR_INSERTUserInfo_LoginLog
5 go
6 --触发器创建在UserInfo表上 当对UserInfo表执行INSERT操作后 自动执行触发器中的SQL语句
7 CREATE TRIGGER TR_INSERTUserInfo_LoginLog
8 ON UserInfo
9 FOR INSERT
10 AS
11 BEGIN
12 --定义接受新建用户ID的参数
13 DECLARE @userID VARCHAR(50);
14 --查询INSERTED临时表获取新建用户ID
15 SELECT @userID=UserID FROM Inserted
16 --向用户登录日志表中添加新建用户登录日志
17 INSERT INTO LoginLog VALUES(@userID,getDate())
18 END
19 GO
20
21 IF EXISTS(SELECT * FROM sysobjects WHERE xtype='TR' AND [name]='TR_Update_UserInfo_ManagerLog')
22 DROP TRIGGER TR_Update_UserInfo_ManagerLog
23 GO
24 CREATE TRIGGER TR_Update_UserInfo_ManagerLog
25 ON UserInfo
26 FOR UPDATE
27 AS
28 --接受被更新用户信息的ID
29 DECLARE @userId INT
30 --接受更新前用户密码的变量
31 DECLARE @oldPwd VARCHAR(50)
32 --接受更新后用户密码的变量
33 DECLARE @newPwd VARCHAR(50)
34 --接受更新前用户邮件的变量
35 DECLARE @oldEmail VARCHAR(50)
36 --接受更新后用户邮件的变量
37 DECLARE @newEmail VARCHAR(50)
38 --从DELETED临时表中获取数据更新前用户数据
39 SELECT @userId=UserId,@oldPwd=password,@oldEmail=Email FROM Deleted
40 --从INSERTED临时表中获取数据更新后的用户数据
41 SELECT @newPwd=password,@newEmail=Email FROM Inserted
42 --向系统日志表中插入数据
43 INSERT INTO managerlog VALUES('修改ID为:['+CAST(@userId AS VARCHAR(5))+']用户信息:<br/>Password:{'+@oldPwd+'}-->Password:{'+@newPwd+'}<br/>Email:{'+@oldEmail+'}-->{'+@newEmail+'}',getDate())
44 Go
45
46
47 --创建当用户表插入新数据时,添加工资表对应记录的触发器
48 IF EXISTS(SELECT * FROM sysobjects WHERE [xtype]='TR' AND [name]='Insert_Emp_EmpPayment')
49 DROP TRIGGER Insert_Emp_EmpPayment
50 go
51 CREATE TRIGGER Insert_Emp_EmpPayment
52 ON Employee1
53 FOR INSERT
54 AS
55 DECLARE @empId INT
56 SELECT @empId=EmpId FROM Inserted
57 INSERT INTO EmpPayMent VALUES(@empId,800.00,null)
58 go
59
60 --创建当向工资表插入数据时,更新工资表中员工奖金
61 IF EXISTS(SELECT * FROM sysobjects WHERE [xtype]='TR' AND [name]='Insert_EmpPayment')
62 DROP TRIGGER Insert_EmpPayment
63 go
64 CREATE TRIGGER Insert_EmpPayment
65 ON EmpPayMent
66 FOR INSERT
67 AS
68 DECLARE @empId INT
69 SELECT @empId=EmpId FROM Inserted
70 UPDATE EmpPayMent SET Bonus=50.00 WHERE EmpID=@empId
71 go

转载于:https://www.cnblogs.com/yerenno1/articles/2036234.html

sqlserver触发器例子 一﹕ 触发器是一种特殊的存储过程﹐它不能被显式地调用﹐而是在往表中插入记录﹑更新记录或者删除记录时被自动地激活。所以触发器可以用来实现对表实施复杂的完整性约`束。 二﹕ SQL Server为每个触发器都创建了两个专用表﹕Inserted表和Deleted表。这两个表由系统来维护﹐它们存在于内存中而不是在数据库中。这两个表的结构总是与被该触发器作用的表的结构相同。触发器执行 完成后﹐与该触发器相关的这两个表也被删除。 Deleted表存放由于执行Delete或Update语句而要从表中删除的所有行。 Inserted表存放由于执行Insert或Update语句而要向表中插入的所有行。 三﹕Instead of 和 After触发器 SQL Server2000提供了两种触发器﹕Instead of 和After 触发器。这两种触发器的差别在于他们被激活的同﹕ Instead of触发器用于替代引起触发器执行的T-SQL语句。除表之外﹐Instead of 触发器也可以用于视图﹐用来扩展视图可以支持的更新操作。 After触发器在一个Insert,Update或Deleted语句之后执行﹐进行约束检查等动作都在After触发器被激活之前发生。After触发器只能用于表。 一个表或视图的每一个修改动作(insert,update和delete)都可以有一个instead of 触发器﹐一个表的每个修改动作都可以有多个After触发器。 四﹕触发器的执行过程 如果一个Insert﹑update或者delete语句违反了约束﹐那幺After触发器不会执行﹐因为对约束的检查是在After触发器被激动之前发生的。所以After触发器不能超越约束。 Instead of 触发器可以取代激发它的操作来执行。它在Inserted表和Deleted表刚刚建立﹐其它任何操作还没有发生时被执行。因为Instead of 触发器在约束之前执行﹐所以它可以对约束进行一些预处理。 五﹕使用T-SQL语句来创建触发器 基本语句如下﹕ create trigger trigger_name on {table_name | view_name} {for | After | Instead of } [ insert, update,delete ] as sql_statement 六﹕相关示例﹕ 1﹕在Orders表中建立触发器﹐当向Orders表中插入一条订单记录时﹐检查goods表的货品状态status是否为1(正在整理)﹐是﹐则不能往Orders表加入该订单。 create trigger orderinsert on orders after insert as if (select status from goods,inserted where goods.name=inserted.goodsname)=1 begin print 'the goods is being processed' print 'the order cannot be committed' rollback transaction --回滚﹐避免加入 end 2﹕在Orders表建立一个插入触发器﹐在添加一条订单时﹐减少Goods表相应的货品记录中的库存。 create trigger orderinsert1 on orders after insert as update goods set storage=storage-inserted.quantity from goods,inserted where goods.name=inserted.goodsname 3﹕在Goods表建立删除触发器﹐实现Goods表和Orders表的级联删除。 create trigger goodsdelete on goods after delete as delete from orders where goodsname in (select name from deleted) 4﹕在Orders表建立一个更新触发器﹐监视Orders表的订单日期(OrderDate)列﹐使其不能手工修改. create trigger orderdateupdate on orders after update as if update(orderdate) begin raiserror(' orderdate cannot be modified',10,1) rollback transaction end 5﹕在Orders表建立一个插入触发器﹐保证向Orders表插入的货品名必须要在Goods表中一定存在。 create trigger orderinsert3 on orders after insert as if (select count(*) from goods,inserted where goods.name=inserted.goodsname)=0 begin print ' no entry in goods for this order' rollback transaction end --insert 触发器 create trigger tri_infoDetails_i on info_details after insert as declare @id int begin --delete from info_details where id= select @id=id from inserted; insert into info_details_index(TYPE,TITLE,content,POST_TIME,FLAG) select type,title,content,getdate(),1 from info_details where id=@id; --update info_details_index set content=content end; -- update触发器 --select top 0 type,title,content,getdate() as post_time,1 as flag into info_details_index from info_details; create trigger tri_infoDetails_u on info_details after update as declare @id int begin if exists(select 1 from inserted) if exists(select 1 from deleted) begin select @id=id from inserted; insert into info_details_index(TYPE,TITLE,content,POST_TIME,FLAG)select type,title,content,getdate(),-1 from info_details where id=@id; insert into info_details_index(TYPE,TITLE,content,POST_TIME,FLAG)select type,title,content,getdate(),1 from info_details where id=@id; end --update info_details_index set content=content end --delete触发器 create trigger tri_infoDetails_d on info_details after delete as declare @id int begin if exists(select 1 from deleted) begin insert into info_details_index(TYPE,TITLE, POST_TIME,FLAG) select type,title, getdate(),-1 from deleted info_details ; end end
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值