Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lsauer/7862119 to your computer and use it in GitHub Desktop.
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
/*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
@alexgman
Copy link

so what do you do if multiple processes (triggers or other) are trying to update the same data ? deadlocked.,

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment