2017-08-15 14 views
0

我正在使用Sql服務器,並且我在node.js中有一個函數,我希望每次在特定表中插入一個新行時執行該函數。在Sql Server中插入時調用node.js函數

這是我希望在表中進行更改時運行的代碼。

private sql = require('mssql'); 
private currentID: any; 

`private config = { 
user: 'sa', 
password: 'sa', 
server: '192.168.100.2', 
port: '1433', 
database: 'test1', 
connectionTimeout: 100000,}; 
` 
public checkDatabase() { 
    this.sql.connect(this.config).then((connection: any) => { 
     new this.sql.Request(connection).query('SELECT EventID FROM Events ORDER BY EventID DESC').then((recordset: any) => { 

      console.log(recordset.recordset[0].EventID); 
      if (this.currentID == recordset.recordset[0].EventID) { 
       console.log("They are the same " + this.currentID + " " + recordset.recordset[0].EventID); 
      } 
      else { 
       console.log("Not the same " + this.currentID + " " + recordset.recordset[0].EventID); 
      } 
      this.currentID = recordset.recordset[0].EventID; 
     }); 
    }); 
} 

有什麼建議嗎?

+0

你應該創建插入觸發器 –

+0

通常這是不可能的。如果從應用程序中插入一行,則無法通知您。儘管你可以嘗試爲所有保存功能創建裝飾器。 – StanislavL

+0

@JúliusMarko你可以給我更多的細節,我不太瞭解觸發器 – DavidS

回答

0

的一般方法是創建用於插入操作的觸發器 - 指定的代碼將在給定的表中的每個插入後執行:

CREATE TRIGGER name_of_your_trigger 
ON test1.Events 
AFTER INSERT 
AS 
    /* here you should specify what do you want to do, for instance print something: */ 
    print "Hello world" 
GO 

看到文檔的更多信息:https://docs.microsoft.com/en-us/sql/t-sql/statements/create-trigger-transact-sql