Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server trigger on specific column updated

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
like image 681
Pradeep Avatar asked Nov 29 '16 11:11

Pradeep


People also ask

How do I check if a column is updated in a trigger?

SQL Server COLUMNS_UPDATED() Function for Triggers. This function is used to know the inserted or updated columns of a table or view. It returns a VARBINARY stream that by using a bitmask allows you to test for multiple columns.

How can I tell which columns were changed in a SQL Server UPDATE?

Using a SQL Server trigger to check if a column is updated, there are two ways this can be done; one is to use the function update(<col name>) and the other is to use columns_updated().

How updated value is triggered in SQL Server?

The following Trigger is fetching the CustomerId of the updated record. In order to find which column is updated, you will need to use UPDATE function and pass the Column name of the Table to it. The UPDATE function will return TRUE for a Column if its value was updated else it will return false.

Can I create trigger on single column value?

You can't trigger on a particular column update in SQL. It is applied on a row.


1 Answers

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
like image 133
Mr. Bhosale Avatar answered Sep 28 '22 11:09

Mr. Bhosale