Created
November 13, 2014 00:24
-
-
Save BryanWilhite/cada52967ae03b1aadbc to your computer and use it in GitHub Desktop.
tSQL: UPDATE Trigger Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ScTriggerLog]') AND type in (N'U')) | |
BEGIN | |
DROP TABLE [dbo].[ScTriggerLog] | |
END | |
GO | |
CREATE TABLE | |
[dbo].[ScTriggerLog] | |
( | |
[ScTriggerLogId] INT IDENTITY (1, 1) NOT NULL | |
, [EntryStamp] DATETIME NOT NULL | |
, [Log] NVARCHAR(1024) NOT NULL | |
) | |
GO | |
IF EXISTS (SELECT name FROM sys.objects WHERE name = 'SclTestTrigger' AND type = 'TR') | |
DROP TRIGGER dbo.SclTestTrigger; | |
GO | |
CREATE TRIGGER dbo.SclTestTrigger | |
ON [dbo].[AssetHistory] | |
AFTER UPDATE | |
AS | |
IF UPDATE(OwnerID) AND EXISTS(SELECT * FROM inserted) AND EXISTS(SELECT * FROM deleted) | |
BEGIN | |
DECLARE @PreviousOwnerId NVARCHAR(50), @CurrentOwnerId NVARCHAR(50) | |
SELECT @PreviousOwnerId = OwnerID FROM deleted | |
SELECT @CurrentOwnerId = OwnerID FROM inserted | |
INSERT INTO | |
[dbo].[ScTriggerLog] | |
SELECT | |
[EntryStamp] = GETDATE() | |
, [Log] = 'Previous Owner ID: ' + ISNULL(@PreviousOwnerId, '[NULL]') + | |
' Current Owner ID: ' + ISNULL(@CurrentOwnerId, '[NULL]') | |
END; | |
GO |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment