简体   繁体   English

如何在每次创建行时运行SQL语句?

[英]How to run a SQL statement every time a row is created?

We are using an ERP system which uses SQL Server. 我们正在使用一个使用SQL Server的ERP系统。 There is a function which creates a row 'A' in a specific table and populates it with data from another row 'B' of another table. 有一个函数在特定表中创建一行'A',并用另一个表的另一行'B'中的数据填充它。 For some reason the programmer thought, one would need only certain values of 'B' in 'A'. 由于某些原因,程序员认为,“A”中只需要某些“B”值。 So only the values of some columns in 'B' are copied. 因此,只复制'B'中某些列的值。

Now I want more columns to be copied than the program copies. 现在我想要复制比程序副本更多的列。 The columns are there but they don't get copied. 列在那里,但它们不会被复制。

The program offers a way to run a script before the SQL statement, which creates the row, is executed. 该程序提供了一种在执行创建行的SQL语句之前运行脚本的方法。 So the problem here is, I don't know the id of the row which will be created. 所以这里的问题是,我不知道将要创建的行的id。 And even if I would, the row isn't created yet to alter it. 即使我愿意,也没有创建行来改变它。

Is there a way in SQL Server to run a SQL script every time after a row is created in a specific table? 在特定表中创建行后,SQL Server中是否有一种方法可以运行SQL脚本?

Thanks for the help. 谢谢您的帮助。

Yes - those are called triggers . 是的 - 这些被称为触发器

You can write triggers that get fired after INSERT , UPDATE or DELETE - or they can be INSTEAD OF triggers, too - if you need to completely take control of an operation. 您可以编写在INSERTUPDATEDELETE之后触发的触发器 - 或者它们也可以是INSTEAD OF触发器 - 如果您需要完全控制操作。

In your case, I believe an AFTER INSERT trigger should be just fine: 在你的情况下,我相信AFTER INSERT触发器应该没问题:

CREATE TRIGGER TrgCopyAdditionalColumns
ON dbo.TableA
AFTER INSERT 
AS  
    -- the newly inserted row (there could be **multiple!**)
    -- will be stored in the `Inserted` pseudo table, which has the 
    -- exact same structure as your "TableB" table - just pick out
    -- the columns you need to insert into "TableA" from here
    INSERT INTO dbo.TableA (Col1, Col2, ..., ColN)
       SELECT 
           b.Col1, b.Col2, ..., b.ColN
       FROM 
           dbo.TableB AS b
       INNER JOIN
           -- somehow, you need to connect your Table B's rows to the
           -- newly inserted rows for Table A that are present in the 
           -- "Inserted" pseudo table, to get only those rows of data from
           -- Table B that are relevant to the newly inserted Table A rows
           Inserted i ON b.A_ID = i.ID  

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

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