阅读完需:约 3 分钟
触发器是一种特殊类型的存储过程,它不同于之前的我们介绍的存储过程。触发器主要是通过事件进行触发被自动调用执行的。而存储过程可以通过存储过程的名称被调用。
触发器对表进行插入、更新、删除的时候会自动执行的特殊存储过程。触发器一般用在check约束更加复杂的约束上面。触发器和普通的存储过程的区别是:触发器是当对某一个表进行操作。诸如:update、insert、delete这些操作的时候,系统会自动调用执行该表上对应的触发器。SQL Server 2005中触发器可以分为两类:DML触发器和DDL触发器,其中DDL触发器它们会影响多种数据定义语言语句而激发,这些语句有create、alter、drop语句。
相关内容:
1.创建Insert触发器
USE [appsmart]
GO
/****** Object: Trigger [dbo].[notify_trigger] Script Date: 01/25/2017 09:31:28 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
----------------创建触发器
ALTER TRIGGER [dbo].[notify_trigger] ON [dbo].[Table_Test]
AFTER INSERT
AS
BEGIN
DECLARE @userName NVARCHAR(20) --Insert触发器 下面为inserted相当于触发器的一个虚拟插入表
set @userName=(select inserted.userName from inserted)
EXEC testProPush @userName ---调用存储过程并传参 如果传入的参数未变则不会触发
END
2.创建存储过程
USE [appsmart]
GO
/****** Object: StoredProcedure [dbo].[testPro] Script Date: 01/25/2017 09:18:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[testPro](
@userName varchar(50)
)
AS
BEGIN
declare @ServiceUrl as varchar(1000)
PRINT 'http://192.168.0.124:8080/overhaul/iosPush.action?deviceToken='+@userName ---触发触发时传过来的参数
set @ServiceUrl='http://192.168.0.124:8080/overhaul/iosPush.action?deviceToken='+@userName
Declare @Object as Int
Declare @ResponseText as Varchar(8000)
Exec sp_OACreate'MSXML2.XMLHTTP',@Object OUT;
Exec sp_OAMethod @Object, 'open',NULL,'get',@ServiceUrl,'false'
Exec sp_OAMethod @Object,'send'
Exec sp_OAMethod @Object,'responseText',@ResponseText OUTPUT
Select @ResponseText
Exec sp_OADestroy @Object
END
在表中插入数据时触发器会调用接口
INSERT INTO [appsmart].[dbo].[Z_UserInfo] (userAccount, userName,userCode) VALUES
('123112', 'de1222','1');
如果你的表名是demo,接收java接口的@RequestMapping 里也是叫demo, 那么无论你在怎么增加 它都不会跑到这个方法
备注:可能出现错误
SQL Server 阻止了对组件“Ole Automation Procedures”的 过程“sys.sp_OACreate”的访问,因为此组件已作为此服务器安全配置的一部分而被关闭。系统管理员可以通过使用 sp_configure 启用“Ole Automation Procedures”。有关启用“Ole Automation Procedures”的详细信息,请搜索 SQL Server 联机丛书中的“Ole Automation Procedures”。语句已终止。
1.开启 Ole Automation Procedures
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ole Automation Procedures';
GO
2.关闭 Ole Automation Procedures
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
EXEC sp_configure 'Ole Automation Procedures';
GO
3.关闭高级选项
sp_configure 'show advanced options', 0;
GO
RECONFIGURE;
GO