sqlserver数据库触发器调用外部exe,同事可以选择参入参数!
sqlserver使用 master..xp_cmdshell 进行外部exe的执行。
使用master..xp_cmdshell 之前需要在据库中启用xp_cmdshell ,启用和关闭方式如下:
--开启xp_cmdshell:
exec sp_configure 'show advanced options', 1;
reconfigure;
exec sp_configure 'xp_cmdshell', 1;
reconfigure;
exec sp_configure 'show advanced options', 0;
reconfigure;
--关闭xp_cmdshell:
exec sp_configure 'show advanced options', 1;
reconfigure;
exec sp_configure 'xp_cmdshell', 0;
reconfigure;
exec sp_configure 'show advanced options', 0;
reconfigure;
外部程序物理路径:“D:\Debug\TEST.exe”
其中,exe程序最好是控制台应用程序,自己执行完成后自己可以进行关闭的程序,否则数据库中会一直进行循环。
第一种,简单的执行外部exe程序:
数据库某个表格中写触发器:
1 USE [dt_teststep]
2 GO
3
4 SET ANSI_NULLS ON
5 GO
6
7 SET QUOTED_IDENTIFIER ON
8 GO
9
10 CREATE TRIGGER [dbo].[tritest]
11 ON [dbo].[tb_test]
12 FOR UPDATE --更改数据触发(insert、delete)
13 AS
14 BEGIN
15 EXEC master..xp_cmdshell 'D:\Debug\TEST.exe'
16
17 SET NOCOUNT ON;
18
19
20 END
21 GO
当表格tb_test中数据更新修改时就会触发外部的exe程序。
第二种,外部程序需要传入参数
这里用控制台应用程序,
static void Main(string[] args){}
其中args为exe程序接收的传入的参数。
数据库中的触发器写法如下:
USE [dt_teststep]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TRIGGER [dbo].[tritest]
ON [dbo].[tb_test]
FOR UPDATE
AS
BEGIN
declare @Type varchar(50) ,@Result varchar(100)
set @Type='参数1'
set @Result = 'cmd.exe /c D:\Debug\TEST.exe '+@Type+' "参数2"'
EXEC master..xp_cmdshell @Result
SET NOCOUNT ON;
-- Insert statements for trigger here
END
GO
与第一种不同的是,带有参数,外部程序调用时改为先启动cmd,然后在进行exe的执行。
其中,参数1作为测试,声明变量,参数2 为直接写入的参数。
在exe程序中接收的参数就是string[] args={"参数1","参数2"};
程序中对参数进行操作即可。