简体   繁体   English

触发器-插入和删除示例之后

[英]Trigger - After insert and delete example

I have a requirement as a trigger should get fired when any row is inserted or deleted from table FAB which contains num as unique value. 我有一个要求,因为当从表FAB中插入或删除任何包含num作为唯一值的行时,应该触发触发器。 and depending upon that num value, another table should be update. 并根据该num值,应更新另一个表。

eg 例如

FAB table

num code   trs
10  A2393  80
20  B3445  780

Reel table

reelnr  num  use flag
340345  10   500  1

when num 10 from FAB table gets deleted(or any new num gets inserted), the trigger should get fired and should check the reel table which contains that num value and give the reelnr. 当FAB表中的num 10被删除(或插入任何新的num)时,触发器应被触发并应检查包含该num值的卷轴表并提供reelnr。

How to proceed with this? 如何进行呢?

you can Use Inserted & Deleted Table in SQL 您可以在SQL中使用插入和删除表

These two tables are special kind of table that are only available inside the scope of the triggers. 这两个表是特殊类型的表,仅在触发器范围内可用。 If you tries to use these tables outside the scope of Triggers then you will get Error. 如果您尝试在触发器的范围之外使用这些表,则会收到错误消息。

Inserted : These table is use to get track of any new records that are insert in the table. Inserted :这些表用于跟踪Inserted表中的任何新记录。 Suppose there are Six rows are inserted in your table then these table will consist of all the six rows that are inserted. 假设在您的表中插入了六行,那么这些表将由所有插入的六行组成。

Deleted : These table is used to track all the Deleted record from your tables. Deleted :这些表用于跟踪表中的所有已删除记录。 Last delete rows will be tracked by these table. 这些表将跟踪最后删除的行。

For Insert : 对于插入:

CREATE TRIGGER TR_AUDIT_Insert
ON Reel_table
FOR INSERT
AS
BEGIN
       INSERT INTO Reel_table (reelnr, num, use, flag)
       SELECT 
           reelnr,
           num,
           use,
           flag          
       FROM 
           INSERTED
END

For Delete : 对于删除:

CREATE TRIGGER TR_AUDIT_Delete
ON Product
FOR DELETED
AS
BEGIN
       INSERT INTO Reel_table (reelnr, num, use, flag)
       SELECT 
           reelnr,
           num,
           use,
           flag          
       FROM 
           DELETED
END

Note : I don't know from where these three reelnr, use flag values you are getting So, Please modify this as per your need. 注意 :我不知道这三个reelnr从哪里来,使用您得到的标志值,所以,请根据需要进行修改。

This is the format of the Triggers that normally we use. 这是我们通常使用的触发器的格式。 You also can do this by using single trigger also I dont know what is your exact requirement If you want to achieve by only single Trigger then you can refer this link : Refer 您还可以通过使用单触发也我不知道什么是您的具体要求,如果你想通过唯一的单触发实现,那么你可以参考以下链接做到这一点: 请参考

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

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