简体   繁体   English

在 DML 插入触发器 (SQL Server) 上执行 Python 脚本

[英]Execute Python script on DML Insert Trigger (SQL Server)

On a SQL Server database, I would like to run an external (Python) script whenever a new row is inserted into a table.在 SQL 服务器数据库上,每当向表中插入新行时,我想运行一个外部 (Python) 脚本。 The Python script needs to process the data from this row. Python 脚本需要处理来自该行的数据。 Is a DML Trigger AFTER INSERT a save method to use here? AFTER INSERT的 DML 触发器是要在此处使用的保存方法吗? I saw several warnings/discouragements in other questions (see, eg, How to run a script on every insert or Trigger script when SQL Data changes ).我在其他问题中看到了几个警告/劝阻(参见,例如, How to run a script on every insert or Trigger script when SQL Data changes )。 From what I understand so far, the script may fail when the INSERT is not yet commited because then the script cannot see/load the row?据我目前的了解,当 INSERT 尚未提交时脚本可能会失败,因为脚本无法看到/加载该行? However, as I understand the example in https://www.mssqltips.com/sqlservertip/5909/sql-server-trigger-example/ , during the execution of the trigger there exists a virtual table named inserted that holds the data being affected by the trigger execution.但是,据我了解https://www.mssqltips.com/sqlservertip/5909/sql-server-trigger-example/中的示例,在触发器执行期间存在一个名为inserted的虚拟表,其中包含受影响的数据通过触发执行。 So technically, I should be able to pass the row that the Python script needs by retrieving it directly from this inserted table?所以从技术上讲,我应该能够通过直接从这个inserted的表中检索来传递 Python 脚本需要的行吗?

I am new to triggers which is why I am asking - so thank you for any clarifaction on best practices here: :)我是触发器的新手,这就是我要问的原因 - 所以感谢您在这里对最佳实践的任何澄清::)

After some testing, I found that the following trigger seems to successfully pass the row from the inserted table to an external Python (SQL Server Machine-Learning-Services) script:经过一些测试,我发现以下触发器似乎成功地将插入表中的行传递给外部 Python (SQL Server Machine-Learning-Services) 脚本:

CREATE TRIGGER index_new_row
ON dbo.triggertesttable
AFTER INSERT
AS

DECLARE @new_row nvarchar(max) = (SELECT * FROM inserted FOR JSON AUTO);
EXEC sp_execute_external_script  @language =N'Python',
@script=N'
import pandas as pd
OutputDataSet = pd.read_json(new_row)
',
@params = N'@new_row nvarchar(max)',
@new_row = @new_row
GO

When testing this with an insert on dbo.triggertesttable , this demo Python script works like a select statement on the inserted table, so it returns all rows that were inserted.当使用dbo.triggertesttable上的插入测试时,此演示 Python 脚本在inserted表上的工作方式类似于 select 语句,因此它返回插入的所有行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM