A Trigger Is A Database Object That Is Attached To A Table
A Trigger Is A Database Object That Is Attached To A Table
A trigger is a database object that is attached to a table. In many aspects it is similar to a stored procedure." As a matter of fact, triggers are often referred to as a "special kind of stored procedure." The main difference between a trigger and a stored procedure is that the former is attached to a table and is only fired when an INSERT, UPDATE or DELETE occurs. You specify the modification action(s) that fire the trigger when it is created. The following shows how to create a trigger that displays the current system time when a row is inserted into the table to which it is attached. SET NOCOUNT ON CREATE TABLE Source (Sou_ID int IDENTITY, Sou_Desc varchar(10)) go CREATE TRIGGER tr_Source_INSERT ON Source FOR INSERT AS PRINT GETDATE() go INSERT Source (Sou_Desc) VALUES ('Test 1') -- Results -Apr 28 2001 9:56AM When to Use Triggers If there is a need to perform a certain action as a result of an INSERT, UPDATE or DELETE and ad hoc SQL (aka SQL Passthrough) is used. For example, let's say you want to send an email to the Sales Manager when an order is entered whose priority is high. When ad hoc SQL is used to insert the Orders row, a trigger is used to determine the Order Priority and send the email when the criteria is met. The following shows a partial code listing of what this looks like. CREATE TABLE Orders (Ord_ID int IDENTITY, Ord_Priority varchar(10)) Go
CREATE TRIGGER tr_Orders_INSERT ON Orders FOR INSERT AS IF (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High') = 1 BEGIN PRINT 'Email Code Goes Here' END Go INSERT Orders (Ord_Priority) VALUES ('High') -- Results -Email Code Goes Here When the stored procedure approach is used you can move the trigger code into the procedure and it looks like this. CREATE PROCEDURE ps_Orders_INSERT @Ord_Priority varchar(10) AS BEGIN TRANSACTION INSERT Orders (Ord_Priority) VALUES (@Ord_Priority) IF @@ERROR <> 0 GOTO ErrorCode IF @Ord_Priority = 'High' PRINT 'Email Code Goes Here' COMMIT TRANSACTION ErrorCode: IF @@TRANCOUNT <> 0 PRINT 'Error Code' Go Let's take a look at the trigger example. The first thing you probably noticed is that the SELECT references a table called inserted. Triggers make use of two special tables called inserted and deleted. The inserted table contains the data referenced in an INSERT before it is actually committed to the database. The deleted table contains the data in the underlying table referenced in a DELETE before it is actually removed from the database. When an UPDATE is issued both tables are used. More specifically, the new data referenced in the UPDATE statement is contained in inserted and the data that is being updated is contained in deleted.
Now we have three rows in Orders whose Ord_Priority is High. Let's insert new rows based on the current contents of Orders to show how a trigger behaves when a multi-row statement is executed. INSERT Orders SELECT Ord_Priority FROM Orders The 'Email Code Here' message is not displayed even though three new rows were added with a priority of High because the IF statement criteria was not satisfied. A trigger fires only once per statement, so the actual COUNT(*) associated with the INSERT is 3. The following shows how to modify the code to handle a multi-row INSERT. ALTER TRIGGER tr_Orders_INSERT ON Orders FOR INSERT AS IF EXISTS (SELECT * FROM inserted WHERE Ord_Priority = 'High') BEGIN DECLARE @Count tinyint SET @Count = (SELECT COUNT(*) FROM inserted WHERE Ord_Priority = 'High') PRINT CAST(@Count as varchar(3))+' row(s) with a priority of High were entered' END go We can test the code using the same INSERT with a SELECT as follows. INSERT Orders SELECT Ord_Priority FROM Orders -- Results -12 row(s) with a priority of High were entered A Real-World Example Those of you familiar with web site management know that counting the traffic on a site is key in determining which areas of the site are being used. Internet Information Server (IIS) has logging capabilities that tracks a number of attributes associated with each visitor. For example, every time a visitor accesses a page on a site that page and the user's information is logged. By default the data is logged in a text file, but you can alter the default behavior and log the data to an ODBCcompliant data store. I used this approach for a client a while back because they wanted a simple way to track the activity for each major area of their site. A major area was defined as the sections listed on the site's main navigation bar (e.g., Home, About Us, Services, ...). The goal was to produce a report that showed the number of visits to each of the main areas of the site on a per month basis. A few of you may be wondering why a
trigger is needed to implement this solution. After all, a SELECT with a WHERE clause to filter the date range and GROUP BY to count the instances per page will do the trick and no triggers are needed. Even on a low-traffic site the number of rows in the logging table grows at a staggering rate. For every page accessed by a visitor, there is at least one row added to the table. When a page contains a reference to a graphic (e.g., .gifs or .jpgs), there is another row created. If a page contains five references to graphics, there are six rows created in the logging table every time it is accessed. CREATE TABLE InetLog (ClientHost varchar(255), LogTime datetime, Target varchar(255)) go CREATE TABLE LogSummary (LogSum_Category varchar(30), LogSum_Count int) go INSERT LogSummary VALUES ('About Us',0) INSERT LogSummary VALUES ('Services',0) InetLog is the main logging table and LogSummary is the summary table. The two main areas of the site are About Us and Services. The goal of the trigger is to update the value in LogSum_Count every time the AboutUs.htm and Services.htm pages are accessed. CREATE TRIGGER tr_InetLog_INSERT ON InetLog FOR INSERT AS IF EXISTS (SELECT * FROM inserted WHERE Target = 'AboutUs.htm') BEGIN UPDATE LogSummary SET LogSum_Count = (SELECT COUNT(*) FROM InetLog WHERE Target = 'AboutUs.htm') WHERE LogSum_Category = 'About Us' END IF EXISTS (SELECT * FROM inserted WHERE Target = 'Services.htm') BEGIN UPDATE LogSummary SET LogSum_Count = (SELECT COUNT(*) FROM InetLog WHERE Target = 'Services.htm') WHERE LogSum_Category = 'Services' END Go
The discussion about UPDATE, DELETE and INSTEAD OF Triggers . UPDATE Trigger An UPDATE trigger is used to perform an action after an update is made on a table. Example : CREATE TRIGGER tr_Orders_UPDATE ON Orders AFTER UPDATE AS --Make sure Priority was changed IF NOT UPDATE(Ord_Priority) RETURN --Determine if Priority was changed to high IF EXISTS (SELECT * FROM inserted a JOIN deleted b ON a.Ord_ID=b.Ord_ID WHERE b.Ord_Priority <> 'High' AND a.Ord_Priority = 'High') BEGIN DECLARE @Count tinyint SET @Count = (SELECT COUNT(*) FROM inserted a JOIN deleted b ON a.Ord_ID=b.Ord_ID WHERE b.Ord_Priority <> 'High' AND a.Ord_Priority = 'High') PRINT CAST(@Count as varchar(3))+' row(s) where changed to a priority of High' END Go DELETE Trigger Once you understand how an UPDATE trigger works a DELETE trigger is easy to implement. In the example shown here it simply counts the number of rows in the deleted table to see how many had a priority of high. CREATE TRIGGER tr_Orders_DELETE ON Orders AFTER DELETE AS --Determine if Order with a Priority of High was deleted IF EXISTS (SELECT * FROM deleted WHERE Ord_Priority = 'High') BEGIN
DECLARE @Count tinyint SET @Count = (SELECT * FROM deleted WHERE Ord_Priority = 'High') PRINT CAST(@Count as varchar(3))+' row(s) where deleted whose priority was High' END Go INSTEAD OF Triggers INSTEAD OF triggers are new to SQL Server 2000. The main reason they were introduced is to facilitate updating Views. I am going to show you how one works, but I am not going to bother with updating a View. Quite frankly I think updating Views is poor application design. I was once told by one of my editors that some of my views on Views reflect my "insular" experience, so if you do not agree with me on this point rest assured you are not alone. An INSTEAD OF Trigger is used to perform an action instead of the one that caused the trigger to be fired. This sounds like double-talk, so I will explain a little more. Let's say you have an INSTEAD OF INSERT trigger defined on a table and an INSERT is executed. A row is not added to the table, but the code in the trigger is fired. The following shows what this looks like. CREATE TRIGGER tr_Orders_INSERT_InsteadOf ON Orders INSTEAD OF INSERT AS PRINT 'Updateable Views are Messy' go The following INSERT produces the message shown, but the row is not added to the table. INSERT Orders (Ord_Priority) VALUES ('High') -- Results -Updateable Views are Messy
Creates a DML, DDL, or logon trigger. A trigger is a special kind of stored procedure that automatically executes when an event occurs in the database server. DML triggers execute when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view. These triggers fire when any valid event is fired, regardless of whether or not any table rows are affected. DDL triggers execute in response to a variety of data definition language (DDL) events. These events primarily correspond to Transact-SQL CREATE, ALTER, and DROP statements, and certain system stored procedures that perform DDL-like operations. Logon triggers fire in response to the LOGON event that is raised when a user sessions is being established. Triggers can be created directly from TransactSQL statements or from methods of assemblies that are created in the Microsoft .NET Framework common language runtime (CLR) and uploaded to an instance of SQL Server. SQL Server allows for creating multiple triggers for any specific statement. Security Note Malicious code inside triggers can run under escalated privileges. For more information on how to mitigate this threat, see Managing Trigger Security. Transact-SQL Syntax Conventions Syntax Copy Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger) CREATE TRIGGER [ schema_name . ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ ,...n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ WITH APPEND ] [ NOT FOR REPLICATION ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > } <dml_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_nameTrigger on a CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE STATISTICS statement (DDL Trigger) CREATE TRIGGER trigger_name ON { ALL SERVER | DATABASE } [ WITH <ddl_trigger_option> [ ,...n ] ] { FOR | AFTER } { event_type | event_group } [ ,...n ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > [ ; ] } <ddl_trigger_option> ::=
[ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_nameTrigger on a LOGON event (Logon Trigger) CREATE TRIGGER trigger_name ON ALL SERVER [ WITH <logon_trigger_option> [ ,...n ] ] { FOR| AFTER } LOGON AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME < method specifier > [ ; ] } <logon_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_name Arguments schema_name Is the name of the schema to which a DML trigger belongs. DML triggers are scoped to the schema of the table or view on which they are created. schema_name cannot be specified for DDL or logon triggers. trigger_name Is the name of the trigger. A trigger_name must comply with the rules for identifiers, except that trigger_name cannot start with # or ##. table | view Is the table or view on which the DML trigger is executed and is sometimes referred to as the trigger table or trigger view. Specifying the fully qualified name of the table or view is optional. A view can be referenced only by an INSTEAD OF trigger. DML triggers cannot be defined on local or global temporary tables. DATABASE Applies the scope of a DDL trigger to the current database. If specified, the trigger fires whenever event_type or event_group occurs in the current database. ALL SERVER Applies the scope of a DDL or logon trigger to the current server. If specified, the trigger fires whenever event_type or event_group occurs anywhere in the current server. WITH ENCRYPTION Obfuscates the text of the CREATE TRIGGER statement. Using WITH ENCRYPTION prevents the trigger from being published as part of SQL Server replication. WITH ENCRYPTION cannot be specified for CLR triggers. EXECUTE AS Specifies the security context under which the trigger is executed. Enables you to control which user account the instance of SQL Server uses to validate permissions on any database objects that are referenced by the trigger. For more information, seeEXECUTE AS Clause (Transact-SQL). FOR | AFTER
AFTER specifies that the DML trigger is fired only when all operations specified in the triggering SQL statement have executed successfully. All referential cascade actions and constraint checks also must succeed before this trigger fires. AFTER is the default when FOR is the only keyword specified. AFTER triggers cannot be defined on views. INSTEAD OF Specifies that the DML trigger is executed instead of the triggering SQL statement, therefore, overriding the actions of the triggering statements. INSTEAD OF cannot be specified for DDL or logon triggers. At most, one INSTEAD OF trigger per INSERT, UPDATE, or DELETE statement can be defined on a table or view. However, you can define views on views where each view has its own INSTEAD OF trigger. INSTEAD OF triggers are not allowed on updatable views that use WITH CHECK OPTION. SQL Server raises an error when an INSTEAD OF trigger is added to an updatable view WITH CHECK OPTION specified. The user must remove that option by using ALTER VIEW before defining the INSTEAD OF trigger. { [ DELETE ] [ , ] [ INSERT ] [ , ] [ UPDATE ] } Specifies the data modification statements that activate the DML trigger when it is tried against this table or view. At least one option must be specified. Any combination of these options in any order is allowed in the trigger definition. For INSTEAD OF triggers, the DELETE option is not allowed on tables that have a referential relationship specifying a cascade action ON DELETE. Similarly, the UPDATE option is not allowed on tables that have a referential relationship specifying a cascade action ON UPDATE. event_type Is the name of a Transact-SQL language event that, after execution, causes a DDL trigger to fire. Valid events for DDL triggers are listed in DDL Events. event_group Is the name of a predefined grouping of Transact-SQL language events. The DDL trigger fires after execution of any Transact-SQL language event that belongs to event_group. Valid event groups for DDL triggers are listed in DDL Event Groups. After the CREATE TRIGGER has finished running, event_group also acts as a macro by adding the event types it covers to the sys.trigger_events catalog view. WITH APPEND Specifies that an additional trigger of an existing type should be added. WITH APPEND cannot be used with INSTEAD OF triggers or if AFTER trigger is explicitly stated. WITH APPEND can be used only when FOR is specified, without INSTEAD OF or AFTER, for backward compatibility reasons. WITH APPEND cannot be specified if EXTERNAL NAME is specified (that is, if the trigger is a CLR trigger). Important WITH APPEND will be removed in the next version of MicrosoftSQL Server. Do not use WITH APPEND in new development work, and plan to modify applications that currently use it. NOT FOR REPLICATION
Indicates that the trigger should not be executed when a replication agent modifies the table that is involved in the trigger. For more information, see Controlling Constraints, Identities, and Triggers with NOT FOR REPLICATION. sql_statement Is the trigger conditions and actions. Trigger conditions specify additional criteria that determine whether the tried DML, DDL, or logon events cause the trigger actions to be performed. The trigger actions specified in the Transact-SQL statements go into effect when the operation is tried. Triggers can include any number and kind of Transact-SQL statements, with exceptions. For more information, see Remarks. A trigger is designed to check or change data based on a data modification or definition statement; it should not return data to the user. The Transact-SQL statements in a trigger frequently include control-of-flow language. DML triggers use the deleted and inserted logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined, that is, the table on which the user action is tried. The deleted and inserted tables hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use: Copy SELECT * FROM deleted For more information, see Using the inserted and deleted Tables. DDL and logon triggers capture information about the triggering event by using the EVENTDATA (Transact-SQL) function. For more information, see Using the EVENTDATA Function. SQL Server allows for the update of text, ntext, or image columns through the INSTEAD OF trigger on tables or views. Important ntext , text, and image data types will be removed in a future version of MicrosoftSQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. Both AFTER and INSTEAD OF triggers support varchar(MAX), nvarchar(MAX), and varbinary(MAX) data in the inserted and deleted tables. < method_specifier > For a CLR trigger, specifies the method of an assembly to bind with the trigger. The method must take no arguments and return void. class_name must be a valid SQL Server identifier and must exist as a class in the assembly with assembly visibility. If the class has a namespace-qualified name that uses '.' to separate namespace parts, the class name must be delimited by using [ ] or " " delimiters. The class cannot be a nested class. Note By default, the ability of SQL Server to run CLR code is off. You can create, modify, and drop database objects that reference managed code modules, but these references will not execute in an instance of SQL Server unless the clr
enabled Option is enabled by using sp_configure. Remarks DML Triggers DML triggers are frequently used for enforcing business rules and data integrity. SQL Server provides declarative referential integrity (DRI) through the ALTER TABLE and CREATE TABLE statements. However, DRI does not provide crossdatabase referential integrity. Referential integrity refers to the rules about the relationships between the primary and foreign keys of tables. To enforce referential integrity, use the PRIMARY KEY and FOREIGN KEY constraints in ALTER TABLE and CREATE TABLE. If constraints exist on the trigger table, they are checked after the INSTEAD OF trigger execution and before the AFTER trigger execution. If the constraints are violated, the INSTEAD OF trigger actions are rolled back and the AFTER trigger is not fired. The first and last AFTER triggers to be executed on a table can be specified by using sp_settriggerorder. Only one first and one last AFTER trigger for each INSERT, UPDATE, and DELETE operation can be specified on a table. If there are other AFTER triggers on the same table, they are randomly executed. If an ALTER TRIGGER statement changes a first or last trigger, the first or last attribute set on the modified trigger is dropped, and the order value must be reset by using sp_settriggerorder. An AFTER trigger is executed only after the triggering SQL statement has executed successfully. This successful execution includes all referential cascade actions and constraint checks associated with the object updated or deleted. If an INSTEAD OF trigger defined on a table executes a statement against the table that would ordinarily fire the INSTEAD OF trigger again, the trigger is not called recursively. Instead, the statement is processed as if the table had no INSTEAD OF trigger and starts the chain of constraint operations and AFTER trigger executions. For example, if a trigger is defined as an INSTEAD OF INSERT trigger for a table, and the trigger executes an INSERT statement on the same table, the INSERT statement executed by the INSTEAD OF trigger does not call the trigger again. The INSERT executed by the trigger starts the process of performing constraint actions and firing any AFTER INSERT triggers defined for the table. If an INSTEAD OF trigger defined on a view executes a statement against the view that would ordinarily fire the INSTEAD OF trigger again, it is not called recursively. Instead, the statement is resolved as modifications against the base tables underlying the view. In this case, the view definition must meet all the restrictions for an updatable view. For a definition of updatable views, see Modifying Data Through a View. For example, if a trigger is defined as an INSTEAD OF UPDATE trigger for a view, and the trigger executes an UPDATE statement referencing the same view, the UPDATE statement executed by the INSTEAD OF trigger does not call the trigger again. The UPDATE executed by the trigger is processed against the view as if the view did not have an INSTEAD OF trigger. The columns changed by the UPDATE must be resolved to a single base table. Each modification to an underlying base table starts the chain of applying constraints and firing AFTER triggers defined for the table.
Testing for UPDATE or INSERT Actions to Specific Columns You can design a Transact-SQL trigger to perform certain actions based on UPDATE or INSERT modifications to specific columns. Use UPDATE() or COLUMNS_UPDATED in the body of the trigger for this purpose. UPDATE() tests for UPDATE or INSERT tries on one column. COLUMNS_UPDATED tests for UPDATE or INSERT actions that are performed on multiple columns and returns a bit pattern that indicates which columns were inserted or updated. Trigger Limitations CREATE TRIGGER must be the first statement in the batch and can apply to only one table. A trigger is created only in the current database; however, a trigger can reference objects outside the current database. If the trigger schema name is specified to qualify the trigger, qualify the table name in the same way. The same trigger action can be defined for more than one user action (for example, INSERT and UPDATE) in the same CREATE TRIGGER statement. INSTEAD OF DELETE/UPDATE triggers cannot be defined on a table that has a foreign key with a cascade on DELETE/UPDATE action defined. Any SET statement can be specified inside a trigger. The SET option selected remains in effect during the execution of the trigger and then reverts to its former setting. When a trigger fires, results are returned to the calling application, just like with stored procedures. To prevent having results returned to an application because of a trigger firing, do not include either SELECT statements that return results or statements that perform variable assignment in a trigger. A trigger that includes either SELECT statements that return results to the user or statements that perform variable assignment requires special handling; these returned results would have to be written into every application in which modifications to the trigger table are allowed. If variable assignment must occur in a trigger, use a SET NOCOUNT statement at the start of the trigger to prevent the return of any result sets. Although a TRUNCATE TABLE statement is in effect a DELETE statement, it does not activate a trigger because the operation does not log individual row deletions. However, only those users with permissions to execute a TRUNCATE TABLE statement need be concerned about inadvertently circumventing a DELETE trigger this way. The WRITETEXT statement, whether logged or unlogged, does not activate a trigger. The following Transact-SQL statements are not allowed in a DML trigger: ALTER DATABASE CREATE DATABASE DROP DATABASE LOAD DATABASE LOAD LOG RECONFIGURE RESTORE DATABASE RESTORE LOG Additionally, the following Transact-SQL statements are not allowed inside the body of a DML trigger when it is used against the table or view that is the target of the triggering action. CREATE INDEX (including CREATE ALTER INDEX DROP
SPATIAL INDEX and CREATE XML INDEX) DBCC DBREINDEX ALTER PARTITION FUNCTION
ALTER TABLE when used to do the following: Add, modify, or drop columns. Switch partitions. Add or drop PRIMARY KEY or UNIQUE constraints. Note Because SQL Server does not support user-defined triggers on system tables, we recommend that you do not create user-defined triggers on system tables. DDL Triggers DDL triggers, like standard triggers, execute stored procedures in response to an event. But unlike standard triggers, they do not execute in response to UPDATE, INSERT, or DELETE statements on a table or view. Instead, they primarily execute in response to data definition language (DDL) statements. These include CREATE, ALTER, DROP, GRANT, DENY, REVOKE, and UPDATE STATISTICS statements. Certain system stored procedures that perform DDL-like operations can also fire DDL triggers. Important Test your DDL triggers to determine their responses to system stored procedure execution. For example, the CREATE TYPE statement and the sp_addtype and sp_rename stored procedures will fire a DDL trigger that is created on a CREATE_TYPE event. For more information about DDL triggers, see DDL Triggers. DDL triggers do not fire in response to events that affect local or global temporary tables and stored procedures. Unlike DML triggers, DDL triggers are not scoped to schemas. Therefore, functions such as OBJECT_ID, OBJECT_NAME, OBJECTPROPERTY, and OBJECTPROPERTYEX cannot be used for querying metadata about DDL triggers. Use the catalog views instead. For more information, see Getting Information About DDL Triggers. Note Server-scoped DDL triggers appear in the SQL Server Management Studio Object Explorer in the Triggers folder. This folder is located under the Server Objects folder. Database-scoped DDL Triggers appear in the Database Triggers folder. This folder is located under the Programmability folder of the corresponding database. Logon Triggers Logon triggers execute stored procedures in response to a LOGON event. This event is raised when a user session is established with an instance of SQL Server. Logon triggers fire after the authentication phase of logging in finishes, but before the user session is actually established. Therefore, all messages originating inside the trigger that would typically reach the user, such as error messages and messages from the
PRINT statement, are diverted to the SQL Server error log. For more information, see Logon Triggers. Logon triggers do not fire if authentication fails. Distributed transactions are not supported in a logon trigger. Error 3969 is returned when a logon trigger containing a distributed transaction is fired. General Trigger Considerations Returning Results The ability to return results from triggers will be removed in a future version of SQL Server. Triggers that return result sets may cause unexpected behavior in applications that are not designed to work with them. Avoid returning result sets from triggers in new development work, and plan to modify applications that currently do this. To prevent triggers from returning result sets, set the disallow results from triggers option to 1. Logon triggers always disallow results sets to be returned and this behavior is not configurable. If a logon trigger does generate a result set, the trigger fails to execute and the login attempt that fired the trigger is denied. Multiple Triggers SQL Server allows for multiple triggers to be created for each DML, DDL, or LOGON event. For example, if CREATE TRIGGER FOR UPDATE is executed for a table that already has an UPDATE trigger, an additional update trigger is created. In earlier versions of SQL Server, only one trigger for each INSERT, UPDATE, or DELETE data modification event is allowed for each table. Recursive Triggers SQL Server also allows for recursive invocation of triggers when the RECURSIVE_TRIGGERS setting is enabled using ALTER DATABASE. Recursive triggers enable the following types of recursion to occur: Indirect recursion With indirect recursion, an application updates table T1. This fires trigger TR1, updating table T2. In this scenario, trigger T2 then fires and updates table T1. Direct recursion With direct recursion, the application updates table T1. This fires trigger TR1, updating table T1. Because table T1 was updated, trigger TR1 fires again, and so on. The following example uses both indirect and direct trigger recursion Assume that two update triggers, TR1 and TR2, are defined on table T1. Trigger TR1 updates table T1 recursively. An UPDATE statement executes each TR1 and TR2 one time. Additionally, the execution of TR1 triggers the execution of TR1 (recursively) and TR2. The inserted and deleted tables for a specific trigger contain rows that correspond only to the UPDATE statement that invoked the trigger. Note The previous behavior occurs only if the RECURSIVE_TRIGGERS setting is enabled by using ALTER DATABASE. There is no defined order in which multiple triggers defined for a specific event are executed. Each trigger should be selfcontained.
Disabling the RECURSIVE_TRIGGERS setting only prevents direct recursions. To disable indirect recursion also, set the nested triggers server option to 0 by using sp_configure. If any one of the triggers performs a ROLLBACK TRANSACTION, regardless of the nesting level, no more triggers are executed. Nested Triggers Triggers can be nested to a maximum of 32 levels. If a trigger changes a table on which there is another trigger, the second trigger is activated and can then call a third trigger, and so on. If any trigger in the chain sets off an infinite loop, the nesting level is exceeded and the trigger is canceled. When a Transact-SQL trigger executes managed code by referencing a CLR routine, type, or aggregate, this reference counts as one level against the 32-level nesting limit. Methods invoked from within managed code do not count against this limit To disable nested triggers, set the nested triggers option of sp_configure to 0 (off). The default configuration allows for nested triggers. If nested triggers is off, recursive triggers is also disabled, regardless of the RECURSIVE_TRIGGERS setting set by using ALTER DATABASE. Note In SQL Server 2000, any AFTER trigger nested inside an INSTEAD OF trigger does not fire when the nested triggers server configuration option is off. In SQL Server 2005 or later, the first AFTER trigger nested inside an INSTEAD OF trigger fires even if the nested triggers server configuration option is set to 0. However, under this setting, later AFTER triggers do not fire. We recommend that you review your applications for nested triggers to determine whether the applications still comply with your business rules with regard to this behavior when the nested triggers server configuration option is set to 0, and then make appropriate modifications. Deferred Name Resolution SQL Server allows for Transact-SQL stored procedures, triggers, and batches to refer to tables that do not exist at compile time. This ability is called deferred name resolution. However, if the Transact-SQL stored procedure, trigger, or batch refers to a table that is defined in the stored procedure or trigger, a warning is issued at creation time only if the compatibility level setting is 65. A warning is issued at compile time if a batch is used. An error message is returned at run time when the table referenced does not exist. For more information, see Deferred Name Resolution and Compilation. Permissions To create a DML trigger requires ALTER permission on the table or view on which the trigger is being created. To create a DDL trigger with server scope (ON ALL SERVER) or a logon trigger requires CONTROL SERVER permission on the server. To create a DDL trigger with database scope (ON DATABASE) requires ALTER ANY DATABASE DDL TRIGGER permission in the current database. Examples A. Using a DML trigger with a reminder message The following DML trigger prints a message to the client when anyone tries to add or change data in the Customer table.
Copy USE AdventureWorks2008R2; GO IF OBJECT_ID ('Sales.reminder1', 'TR') IS NOT NULL DROP TRIGGER Sales.reminder1; GO CREATE TRIGGER reminder1 ON Sales.Customer AFTER INSERT, UPDATE AS RAISERROR ('Notify Customer Relations', 16, 10); GO B. Using a DML trigger with a reminder e-mail message The following example sends an e-mail message to a specified person (MaryM) when the Customer table changes. Copy USE AdventureWorks2008R2; GO IF OBJECT_ID ('Sales.reminder2','TR') IS NOT NULL DROP TRIGGER Sales.reminder2; GO CREATE TRIGGER reminder2 ON Sales.Customer AFTER INSERT, UPDATE, DELETE AS EXEC msdb.dbo.sp_send_dbmail @profile_name = 'AdventureWorks2008R2 Administrator', @recipients = '[email protected]', @body = 'Don''t forget to print a report for the sales force.', @subject = 'Reminder'; GO C. Using a DML AFTER trigger to enforce a business rule between the PurchaseOrderHeader and Vendor tables Because CHECK constraints can reference only the columns on which the columnlevel or table-level constraint is defined, any cross-table constraints (in this case, business rules) must be defined as triggers. The following example creates a DML trigger. This trigger checks to make sure the credit rating for the vendor is good when an attempt is made to insert a new purchase order into the PurchaseOrderHeader table. To obtain the credit rating of the vendor, the Vendor table must be referenced. If the credit rating is too low, a message is displayed and the insertion does not execute. Note To view examples of DML AFTER triggers that update multiple rows, see Multirow
Considerations for DML Triggers. To view examples of DML INSTEAD OF INSERT triggers, see INSTEAD OF INSERT Triggers. Copy USE AdventureWorks2008R2; GO IF OBJECT_ID ('Purchasing.LowCredit','TR') IS NOT NULL DROP TRIGGER Purchasing.LowCredit; GO -- This trigger prevents a row from being inserted in the Purchasing.PurchaseOrderHeader table -- when the credit rating of the specified vendor is set to 5 (below average). CREATE TRIGGER Purchasing.LowCredit ON Purchasing.PurchaseOrderHeader AFTER INSERT AS DECLARE @creditrating tinyint, @vendorid int; IF EXISTS (SELECT * FROM Purchasing.PurchaseOrderHeader p JOIN inserted AS i ON p.PurchaseOrderID = i.PurchaseOrderID JOIN Purchasing.Vendor AS v ON v.BusinessEntityID = p.VendorID WHERE v.CreditRating = 5 ) BEGIN RAISERROR ('This vendor''s credit rating is too low to accept new purchase orders.', 16, 1); ROLLBACK TRANSACTION; RETURN END; GO -- This statement attempts to insert a row into the PurchaseOrderHeader table -- for a vendor that has a below average credit rating. -- The AFTER INSERT trigger is fired and the INSERT transaction is rolled back. INSERT INTO Purchasing.PurchaseOrderHeader (RevisionNumber, Status, EmployeeID, VendorID, ShipMethodID, OrderDate, ShipDate, SubTotal, TaxAmt, Freight) VALUES( 2 ,3 ,261 ,1652 ,4 ,GETDATE()
,GETDATE() ,44594.55 ,3567.564 ,1114.8638); GO D. Using a database-scoped DDL trigger The following example uses a DDL trigger to prevent any synonym in a database from being dropped. Copy USE AdventureWorks2008R2; GO IF EXISTS (SELECT * FROM sys.triggers WHERE parent_class = 0 AND name = 'safety') DROP TRIGGER safety ON DATABASE; GO CREATE TRIGGER safety ON DATABASE FOR DROP_SYNONYM AS RAISERROR ('You must disable Trigger "safety" to drop synonyms!',10, 1) ROLLBACK GO DROP TRIGGER safety ON DATABASE; GO
E. Using a server-scoped DDL trigger The following example uses a DDL trigger to print a message if any CREATE DATABASE event occurs on the current server instance, and uses the EVENTDATA function to retrieve the text of the corresponding Transact-SQL statement. Note For more examples that use EVENTDATA in DDL triggers, see Using the EVENTDATA Function. Copy IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = 'ddl_trig_database') DROP TRIGGER ddl_trig_database ON ALL SERVER; GO CREATE TRIGGER ddl_trig_database
ON ALL SERVER FOR CREATE_DATABASE AS PRINT 'Database Created.' SELECT EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText) [1]','nvarchar(max)') GO DROP TRIGGER ddl_trig_database ON ALL SERVER; GO F. Using a logon trigger The following logon trigger example denies an attempt to log in to SQL Server as a member of the login_test login if there are already three user sessions running under that login. Copy USE master; GO CREATE LOGIN login_test WITH PASSWORD = '3KHJ6dhx(0xVYsdf' MUST_CHANGE, CHECK_EXPIRATION = ON; GO GRANT VIEW SERVER STATE TO login_test; GO CREATE TRIGGER connection_limit_trigger ON ALL SERVER WITH EXECUTE AS 'login_test' FOR LOGON AS BEGIN IF ORIGINAL_LOGIN()= 'login_test' AND (SELECT COUNT(*) FROM sys.dm_exec_sessions WHERE is_user_process = 1 AND original_login_name = 'login_test') > 3 ROLLBACK; END; G. Viewing the events that cause a trigger to fire The following example queries the sys.triggers and sys.trigger_events catalog views to determine which Transact-SQL language events cause trigger safety to fire. safety is created in the previous example. Copy SELECT TE.* FROM sys.trigger_events AS TE
JOIN sys.triggers AS T ON T.object_id = TE.object_id WHERE T.parent_class = 0 AND T.name = 'safety' GO See Also Reference ALTER TABLE (Transact-SQL) ALTER TRIGGER (Transact-SQL) COLUMNS_UPDATED (Transact-SQL) CREATE TABLE (Transact-SQL) DROP TRIGGER (Transact-SQL) ENABLE TRIGGER (Transact-SQL) DISABLE TRIGGER (Transact-SQL) TRIGGER_NESTLEVEL (Transact-SQL) EVENTDATA (Transact-SQL) sys.dm_sql_referenced_entities (Transact-SQL) sys.dm_sql_referencing_entities (Transact-SQL) sys.sql_expression_dependencies (Transact-SQL) sp_help (Transact-SQL) sp_helptrigger (Transact-SQL) sp_helptext (Transact-SQL) sp_rename (Transact-SQL) sp_settriggerorder (Transact-SQL) UPDATE() (Transact-SQL) sys.triggers (Transact-SQL) sys.trigger_events (Transact-SQL) sys.sql_modules (Transact-SQL) sys.assembly_modules (Transact-SQL) sys.server_triggers (Transact-SQL) sys.server_trigger_events (Transact-SQL) sys.server_sql_modules (Transact-SQL) sys.server_assembly_modules (Transact-SQL) Concepts Programming CLR Triggers Using Identifiers As Object Names Getting Information About DML Triggers Getting Information About DDL Triggers Controlling Constraints, Identities, and Triggers with NOT FOR REPLICATION Using Large-Value Data Types Community Content Add FAQ Missing new-line or line-endings
In T-SQL grammer please start a new grammar script in a new line. For example, DDL Trigger should be in new line than method_specifier grammar line. Thanks, Laxmi History 2/16/2011 Laxmi Narsimha Rao ORUGANTI MSFT Triggers in Sql Server A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. <a href="http://www.mindstick.com/Articles/8a50890e-16b5-4fc6-897054ae61a898f9/?Triggers%20in%20SQL %20Server">http://www.mindstick.com/Articles/8a50890e-16b5-4fc6-897054ae61a898f9/?Triggers%20in%20SQL%20Server</a> History 1/13/2011 dummy ahuja Multiple Triggers The statement that multiple triggers are not allowed in earlier versions of SQL Server is incorrect for most earlier versions: SQL 7.0, SQL 2000, SQL 2005, and SQL 2008 all allow multiple triggers for the same event; it is correct only for versions earlier than SQL 7.0 History 1/10/2011 Tom Thomson creation d'un trigger sur une table sql server CREATE TRIGGER [dbo].[NAVIRE_TRIG] ON [dbo].[NAVIRE] for delete AS IF EXISTS (SELECT MARCHANDISE.N_GROS from MARCHANDISE where MARCHANDISE.N_GROS=(SELECT N_GROS FROM deleted) ) BEGIN RAISERROR ('Cette Navire a des marchandises, vous ne pouvez pas la supprimer!', 16, 1); ROLLBACK TRANSACTION; RETURN END;
BEST REGARDS ILIESSE DEBOUCHA History 11/30/2010 iliesse 11/30/2010 iliesse Recursive INSTEAD OF Triggers Hello, From the article: If an INSTEAD OF trigger defined on a table executes a statement against t he table that would ordinarily fire the INSTEAD OF trigger again, the trigger is not called recursively. Instead, the statement is processed as if the table had no INSTEAD OF trigger and starts the chain of constraint operations a nd AFTER trigger executions. For example, if a trigger is defined as an INS TEAD OF INSERT trigger for a table, and the trigger executes an INSERT st atement on the same table, the INSERT statement executed by the INSTEA D OF trigger does not call the trigger again. The INSERT executed by the tri gger starts the process of performing constraint actions and firing any AFT ER INSERT triggers defined for the table. In my business rules, I would like my INSTEAD OF INSERT Trigger execute a DE LETE under certain conditions. It appears that for the same reason, my DELETE I NSTEAD of Trigger is not being fired. Is this the case? Thanks, Jeff History 6/25/2010 Jefffrey C About Example E Hello, The DDL trigger on example E should have a BEGIN and END. That example also drops the trigger right after its been created and may confuse a person interested in learning this topic by practicing with the examples. Also the example does not show the intended message, I modified that example to create an entry on SQL Server log:
IF EXISTS (SELECT * FROM sys.server_triggers WHERE name = 'ddl_trig_database') DROP TRIGGER ddl_trig_database ON ALL SERVER; GO CREATE TRIGGER ddl_trig_database ON ALL SERVER FOR CREATE_DATABASE AS BEGIN DECLARE @Message NVARCHAR(256) SET @Message = 'Database created - ' + EVENTDATA().value('(/EVENT_INST ANCE/TSQLCommand/CommandText)[1]','nvarchar(max)') EXEC master..xp_logevent 50001, @Message, 'ERROR' ROLLBACK END GO Regards, Alberto Morillo SQLCoffee.com