Created
December 8, 2013 18:52
-
-
Save lsauer/7862119 to your computer and use it in GitHub Desktop.
MS-SQL Server/TSQL Trigger: Update a field only when a specific value is set, otherwise set a different condition
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
/*www.technical-programming.com, lo sauer 2013 | |
Target: MS/Microsoft SQL Server 2005 or higher | |
description: Upon update, the rows's timestamp field is set to the current unix-timestamp, | |
unless the timestamp is NULL or Empty. If the timestamp field is supplied in the update | |
statement, the supplied value is set as is. | |
The tstamp field is defined as: | |
[__unixtimestamp] INT NULL | |
The primary key is defined as: | |
[ID] INT IDENTITY (1, 1) NOT NULL | |
*/ | |
CREATE TRIGGER mytableAfterUpdate on mytable | |
FOR UPDATE AS | |
IF UPDATE(__unixtimestamp) | |
BEGIN | |
SET NOCOUNT ON -- Supress the trigger statements in the'affected rows' count | |
UPDATE dbo.[mytable] | |
SET dbo.[mytable].[__unixtimestamp] = Inserted.[__unixtimestamp] /* +1 */ | |
FROM dbo.[mytable],Inserted, Deleted | |
WHERE dbo.[mytable].[ID] = Inserted.[ID] | |
END | |
ELSE | |
BEGIN | |
SET NOCOUNT ON -- Supress the trigger statements in the'affected rows' count | |
UPDATE dbo.[mytable] | |
SET dbo.[mytable].[__unixtimestamp] = (CASE WHEN Inserted.[__unixtimestamp] >'' THEN DATEDIFF(s, '19700101', GetDate()) | |
ELSE Inserted.[__unixtimestamp] END) | |
FROM dbo.[mytable],Inserted | |
WHERE dbo.[mytable].[ID] = Inserted.[ID] | |
END | |
/* Short alternative, for use in a productive environment */ | |
CREATE TRIGGER kurseAfterUpdate on kurse | |
FOR UPDATE AS | |
IF NOT UPDATE(__unixtimestamp) | |
BEGIN | |
SET NOCOUNT ON -- Supress the trigger statements in the'affected rows' count | |
UPDATE dbo.[mytable] | |
SET dbo.[mytable].[__unixtimestamp] = (CASE WHEN Inserted.[__unixtimestamp] >'' THEN DATEDIFF(s, '19700101', GetDate()) | |
ELSE Inserted.[__unixtimestamp] END) | |
FROM dbo.[mytable],Inserted | |
WHERE dbo.[mytable].[ID] = Inserted.[ID] | |
END |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
so what do you do if multiple processes (triggers or other) are trying to update the same data ? deadlocked.,