我是靠谱客的博主 负责草丛,这篇文章主要介绍触发器的基本使用,现在分享给大家,希望可以做个参考。

SQL Server 支持两种类型的触发器AFTER 触发器和INSTEAD OF 触发器

1)INSTEAD OF 触发器表示并不执行其所定义的操作INSERT,UPDATE ,DELETE,而仅是执行触发器本身,既可在表上定义INSTEAD OF 触发器,也可以在视图上定义INSTEAD OF 触发器。
2)AFTER触发器(也叫“FOR”触发器)则会在触发 insert、update 或是delect 动作之后执行。

一个表或视图的每一个修改动作(insert,update和delete)都可以有一个instead of 触发器,一个表的每个修改动作都可以有多个After触发器。
after触发器是在操作成功后,所采取的一些动作
而对于instead of触发器,真正起作用的是触发器里面的动作!

讲解一个简单的insert触发器,
先创建测试表
create table testTable
(
id int identity (1,1),
money int,
)

给测试表创建一个新增的触发器

create trigger firsttrigger		创建触发器		
    on testTable       表名  
    FOR insert       什么条件下触发
    as
    begin
    declare @testcount int;    定义一个变量
    select @testcount=COUNT(*) from testTable; 	变量值等于旧表的统计值
    if not exists (select * from sysobjects where name='testTableTwo')      判断是否有新的表 
        begin             
    		create table testTableTwo(countsum int default(0));      创建新表
    		insert into testTableTwo values(@testcount);   新增数据
        end	
    else update testTableTwo set countsum=@testcount;   修改数据
    if not exists (select * from sysobjects where name='testTable')				
    	begin
    		print '表不存在'        同console.log
    		rollback transaction		事务回滚取消前面所有操作	
    	end
    end      

数据测试
truncate table testTable
insert into testTable Values(22)
select * from testTable
select * from testTableTwo

在这里插入图片描述

insert into testTable Values(222)
insert into testTable Values(23)
insert into testTable Values(24)

在这里插入图片描述

触发器常用查询语句

select * from sysobjects where xtype=‘TR’ 查看数据库中所有的触发器
exec sp_helptext ‘触发器名称’ 查看触发器内容
exec sp_helptrigger 表名 查看触发器属性
alter table 表名 disable trigger 触发器名称 禁用触发器
alter table 表名 enable trigger 触发器名称 启用触发器

最后

以上就是负责草丛最近收集整理的关于触发器的基本使用的全部内容,更多相关触发器内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(165)

评论列表共有 0 条评论

立即
投稿
返回
顶部