sqlserver 實現資料變動觸發資訊

azhai發表於2016-09-23

 

1、建立儲存過程,功能是動態寫入檔案中資訊,可以在觸發器或儲存過程呼叫。

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create proc [dbo].[SP_SendMagToFile]
(
  @path varchar(100),
  @fileName varchar(100), 
  @msg varchar(200)
)
as
begin
  DECLARE   @object   int
  DECLARE   @hr   int
  DECLARE   @src   varchar(255),   @desc   varchar(255)
  Declare   @tmp   int
  declare   @strPath     nvarchar(512)
  Set   @strPath=@path+'\'+@fileName       --組成檔名

  EXEC   @hr   =   sp_OACreate   'Scripting.FileSystemObject',   @object   OUT
  IF   @hr   <>   0
  BEGIN
        EXEC   sp_OAGetErrorInfo   @object,   @src   OUT,   @desc   OUT
        SELECT   hr=convert(varbinary(4),@hr),   Source=@src,   Description=@desc
        RETURN
  END
 
  --建立檔案
  EXEC   @hr   =   sp_OAMethod   @object,   'CreateTextFile',   @tmp   OUTPUT   ,   @strPath
  IF   @hr   <>   0
  BEGIN
        EXEC   sp_OAGetErrorInfo   @object
          RETURN
  END
  --把@msg寫到檔案裡面去
  EXEC   @hr   =   sp_OAMethod   @tmp,   'Write',NULL,   @msg
  IF   @hr   <>   0
  BEGIN
        EXEC   sp_OAGetErrorInfo   @object
          RETURN
  END
  --關閉檔案
  EXEC   @hr   =   sp_OAMethod   @tmp,   'Close',NULL
  IF   @hr   <>   0
  BEGIN
    EXEC   sp_OAGetErrorInfo   @object
    RETURN
  END
end

2、服務端監聽給資料夾是否被更新,如果更新就傳送資訊或執行程式等。

3、這樣可以減少網路傳輸的壓力。

4、也可以執行傳送http,實現更新資料的功能

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

/*
引數說明?
@URL=http請求地址
@status=狀態代?
@returnText=返回?
@object=物件令牌
@errSrc=錯誤源編?
*/
CREATE PROCEDURE P_GET_HttpRequestData(
    @URL varchar(500),
    @status int=0 OUT,
    @returnText varchar(2000)='' OUT
)
AS
BEGIN
    DECLARE @object int,
    @errSrc int
    /*初始化對*/
    EXEC @status = SP_OACreate 'Msxml2.ServerXMLHTTP.3.0', @object OUT
    IF @status <> 0
    BEGIN
     EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
     RETURN
    END

    /*建立連結*/
    EXEC @status= SP_OAMethod @object,'open',NULL,'GET',@URL
    IF @status <> 0
    BEGIN
     EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
     RETURN
    END
    EXEC @status=SP_OAMethod @object,'setRequestHeader','Content-Type','application/x-www-form-urlencoded'
    /*發起請求*/
    EXEC @status= SP_OAMethod @object,'send',NULL 
    IF @status <> 0 
    BEGIN 
     EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
     RETURN
    END
     
    /*獲取返回*/
    EXEC @status= SP_OAGetProperty @object,'responseText',@returnText OUT
    IF @status <> 0 
    BEGIN 
     EXEC SP_OAGetErrorInfo @object, @errSrc OUT, @returnText OUT
     RETURN
    END
END;

 

相關文章