简体   繁体   English

在SQL Server中创建触发器

[英]Create Trigger in SQL Server

I got lost when I wanted to create trigger using the pre-defined "CREATE TRIGGER" of SQL Server 2008 R2. 当我想使用SQL Server 2008 R2的预定义“CREATE TRIGGER”创建触发器时,我迷路了。 Could you please give me a direct SQL statement that I can use to create a trigger, and tell me how to define AFTER, BEFORE, and all that? 你能给我一个直接的SQL语句,我可以用来创建一个触发器,并告诉我如何定义AFTER,BEFORE等等吗?

Also, how can I know the rows UPDATED/INSERTED/DELETED, and use their column values to do operations inside the trigger? 另外,如何知道行UPDATED / INSERTED / DELETED,并使用它们的列值在触发器内执行操作?

The basic syntax is 基本语法是

CREATE TRIGGER YourTriggerName ON dbo.YourTable
FOR|AFTER INSERT, UPDATE, DELETE
AS
BEGIN
     /*Put what ever you want here*/
     UPDATE AnotherTable
          SET SomeColumn = AnotherColumn
     FROM inserted | deleted
END
GO

Databases are set-oriented and triggers are no different. 数据库是面向集合的,触发器也不例外。 A trigger will fire when a given operation is performed and that operation might affect multiple rows. 执行给定操作时该触发器将触发,该操作可能会影响多行。 Thus, the question "Say I want to know the Primary Key of that row" is a misnomer. 因此, "Say I want to know the Primary Key of that row"这个问题是用词不当。 There could be multiple rows inserted. 可能会插入多行。

SQL Server provides two special tables for AFTER triggers named inserted and deleted which represent the rows that were inserted or deleted by an action and are structured identically to the table being affected. SQL Server为名为inserteddeleted AFTER触发器提供了两个特殊表,这些表表示由操作插入或删除的行,其结构与受影响的表的结构相同。 An update trigger might populate both inserted and deleted whereas an insert trigger would only populate the inserted table. 更新触发器可能会填充inserteddeleted而插入触发器只会填充inserted表。

From comments: 来自评论:

but the email recipient will be decided based on a value in a second table, where the foreign key ID is located in the first table (which is the one with trigger 但是电子邮件收件人将根据第二个表中的值来决定,其中外键ID位于第一个表中(具有触发器的表)

The answer to this question is to use the inserted table (which again, you must assume could have multiple rows) to cycle through the rows and send an email. 这个问题的答案是使用inserted表(再次,你必须假设可能有多行)循环遍历行并发送电子邮件。 However, I would recommend against putting email logic in a trigger. 但是,我建议不要将电子邮件逻辑放在触发器中。 Instead, I would recommend putting that logic in a stored procedure and send your email from that. 相反,我建议将该逻辑放在存储过程中并从中发送您的电子邮件。

For reference: Create Trigger 供参考: 创建触发器

A trigger is an event-based process that is "triggered" after a table is changed in some way. 触发器是基于事件的进程,在以某种方式更改表后“触发”。 This will be on DELETE, UPDATE, INSERT, and so forth. 这将是DELETE,UPDATE,INSERT等。 Your BEFORE and AFTER syntax will define whether to run the trigger before or after the event is committed. BEFORE和AFTER语法将定义在提交事件之前或之后是否运行触发器。

That's the short version. 这是短版本。 Check out MSDN . 查看MSDN

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

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