一段trigger codes例子:
插入、刪除和更新的觸發器代碼:
-- dbo.trGroups.SQL
IF EXISTS (
SELECT * FROM sysobjects WHERE
name = 'trGroups' AND type = 'TR')
BEGIN
DROP TRIGGER trGroups
IF NOT EXISTS (
SELECT * FROM sysobjects WHERE
name = 'trGroups' AND type = 'TR')
PRINT 'DROP trGroups SUCCEEDED'
ELSE
PRINT 'DROP trGroups FAILED'
END
ELSE
PRINT 'Attempting to CREATE trGroups'
GO
CREATE TRIGGER dbo.trGroups
ON groups
AFTER INSERT, UPDATE, DELETE
AS
-- This trigger submits a cached rates delete job for modified groups.
-- It also updates the groups' last modified columns for modified groups.
-- It also updates the groups' state (if currently unspecified) based on
-- the (first) state extracted from groups' zip code for new/modified groups.
-- No error checking is currently being performed.
SET NOCOUNT ON -- stop display of rowcount messages
DECLARE
@groupID int,
@deletedCount int,
@returnCode int
SELECT
@deletedCount = COUNT(*)
FROM
deleted WITH (NOLOCK)
IF @deletedCount > 0
BEGIN
DECLARE groupIDCursor CURSOR
FAST_FORWARD
FOR
SELECT DISTINCT
t1.groupID
FROM
(
SELECT
groupID
FROM
inserted WITH (NOLOCK)
UNION
SELECT
groupID
FROM
deleted WITH (NOLOCK)
) as t1
OPEN groupIDCursor
FETCH NEXT
FROM
groupIDCursor
INTO
@groupID
WHILE @@FETCH_STATUS = 0
BEGIN
EXEC @returnCode = dbo.spCachingModuleAddJobDeleteCachedRatesByGroupID
@groupID = @groupID
FETCH NEXT
FROM
groupIDCursor
INTO
@groupID
END
CLOSE groupIDCursor
DEALLOCATE groupIDCursor
END
GO
IF EXISTS (
SELECT * FROM sysobjects WHERE
name = 'trGroups' AND type = 'TR')
PRINT 'CREATE trGroups SUCCEEDED'
ELSE
PRINT 'CREATE trGroups FAILED'
GO
觸發器語句中使用了兩種特殊的表:deleted 表和 inserted 表。
Deleted 表用於儲存 DELETE 和 UPDATE 語句所影響的行的複本。在執行 DELETE 或 UPDATE 語句時,行從觸發器表中刪除,並傳輸到 deleted 表中。Deleted 表和觸發器表通常沒有相同的行。
Inserted 表用於儲存 INSERT 和 UPDATE 語句所影響的行的副本。在一個插入或更新交易處理中,建立行被同時添加到 inserted 表和觸發器表中。Inserted 表中的行是觸發器表中新行的副本。
1.插入操作(Insert)
Inserted表有資料,Deleted表無資料
2.刪除操作(Delete)
Inserted表無資料,Deleted表有資料
3.更新操作(Update)
Inserted表有資料(新資料),Deleted表有資料(舊資料)