[英]How to run a SQL statement every time a row is created?
我们正在使用一个使用SQL Server的ERP系统。 有一个函数在特定表中创建一行'A',并用另一个表的另一行'B'中的数据填充它。 由于某些原因,程序员认为,“A”中只需要某些“B”值。 因此,只复制'B'中某些列的值。
现在我想要复制比程序副本更多的列。 列在那里,但它们不会被复制。
该程序提供了一种在执行创建行的SQL语句之前运行脚本的方法。 所以这里的问题是,我不知道将要创建的行的id。 即使我愿意,也没有创建行来改变它。
在特定表中创建行后,SQL Server中是否有一种方法可以运行SQL脚本?
谢谢您的帮助。
是的 - 这些被称为触发器 。
您可以编写在INSERT
, UPDATE
或DELETE
之后触发的触发器 - 或者它们也可以是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.