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

时间:2015-11-29 09:14:50

标签: sql sql-server

我们正在使用一个使用SQL Server的ERP系统。有一个功能可以创建一行' A'在一个特定的表格中,用另一行的数据填充它' B'另一张桌子。程序员认为,出于某种原因,人们只需要某些“B'在' A'。因此,只有' B'中某些列的值才有。被复制。

现在我想要复制比程序副本更多的列。列在那里,但它们不会被复制。

该程序提供了一种在执行创建行的SQL语句之前运行脚本的方法。所以这里的问题是,我不知道将要创建的行的id。即使我愿意,也没有创建该行来改变它。

在特定表中创建行后,SQL Server中是否有一种方法可以运行SQL脚本?

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

是 - 这些被称为触发器

您可以编写在INSERTUPDATEDELETE之后触发的触发器 - 或者它们也可以是INSTEAD OF触发器 - 如果您需要完全控制一项行动。

在您的情况下,我相信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