5

I have a table with the following columns:

ID | CLIENT_SYNCED_TIME  |  NAME  | DESCRIPTION | LM_TIME

The LM_TIME column will be set automatically by a trigger when any of the other column values get updated.

However I want the LM_TIME .... NOT to get updated by the trigger when the CLIENT_SYNCED_TIME column is updated.

I am using the below trigger right now, which updates the LM_TIME when any of the column value is changed.

Simply I just want to make the trigger not to worry about CLIENT_SYNCED_TIME column. What modifications I have to make to achieve this effect?

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[updateLM_TIME]
ON [dbo].[INSTITUTIONS]
AFTER INSERT, UPDATE 
AS
    UPDATE dbo.INSTITUTIONS
    SET lm_time = CONVERT(DATETIME, CONVERT(VARCHAR(20), GETDATE(), 120))
    WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
GO
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Pradeep
  • 581
  • 3
  • 11
  • 19
  • If there's an `UPDATE` statement and it updates `CLINET_SYNCED_TIME` (and other columns) but happens to set it to the same value it already has, what should happen then? – Damien_The_Unbeliever Nov 29 '16 at 11:27
  • It's not a problem sir.. I just want to make the trigger not to worry about "CLIENT_SYNCED_TIME" column – Pradeep Nov 29 '16 at 11:29
  • Have a look: http://stackoverflow.com/questions/17768608/what-is-the-practical-use-of-timestamp-column-in-sql-server-with-example – Ivan Starostin Nov 29 '16 at 11:34

2 Answers2

9

try this.

USE [lms_db]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[updateLM_TIME]
ON [dbo].[INSTITUTIONS]

AFTER INSERT, UPDATE
AS
    IF UPDATE(ID) or UPDATE(NAME) or UPDATE(DESCRIPTION)
    BEGIN
        UPDATE dbo.INSTITUTIONS
        SET lm_time = CONVERT(DATETIME, CONVERT(VARCHAR(20), GETDATE(), 120))
        WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
    END

Or

AFTER INSERT, UPDATE
AS
    IF UPDATE(CLIENT_SYNCED_TIME)
        PRINT 'Not Updated';
    ELSE
    BEGIN
        UPDATE dbo.INSTITUTIONS
        SET lm_time = CONVERT(DATETIME, CONVERT(VARCHAR(20), GETDATE(), 120))
        WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
        PRINT 'Updated';
    END
sigod
  • 3,514
  • 2
  • 21
  • 44
Mr. Bhosale
  • 3,018
  • 1
  • 17
  • 34
2

thanks to Mr. Bhosale

USE [lms_db]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TRIGGER [dbo].[updateLM_TIME]
ON [dbo].[INSTITUTIONS]

AFTER INSERT, UPDATE 
AS

IF NOT UPDATE(CLIENT_SYNCED_TIME)

BEGIN

UPDATE dbo.INSTITUTIONS
SET lm_time = CONVERT(DATETIME, CONVERT(VARCHAR(20), GETDATE(), 120))
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)

END
Pradeep
  • 581
  • 3
  • 11
  • 19