Create Trigger in SQL Server

前端 未结 3 854
后悔当初
后悔当初 2020-12-11 02:29

I got lost when I wanted to create trigger using the pre-defined \"CREATE TRIGGER\" of SQL Server 2008 R2. Could you please give me a direct SQL statement that I can use to

相关标签:
3条回答
  • 2020-12-11 02:30

    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. 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. An update trigger might populate both inserted and deleted whereas an insert trigger would only populate the inserted table.

    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

    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. 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

    0 讨论(0)
  • 2020-12-11 02:40

    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
    
    0 讨论(0)
  • 2020-12-11 02:51

    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. Your BEFORE and AFTER syntax will define whether to run the trigger before or after the event is committed.

    That's the short version. Check out MSDN.

    0 讨论(0)
提交回复
热议问题