Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Trigger Update

Tags:

tsql

triggers

I have a table with 3 fields [ID, Name, LastUpdated].
LastUpdated has a default value of "GetDate() so it automatically fills itself when a new record is added.

When I instead run an UPDATE on TABLE, I would like to have this field reset itself to the current GetDate().

CREATE TRIGGER dbo.Table1_Updated
   ON  dbo.Table1
   AFTER UPDATE
AS 
BEGIN
    SET NOCOUNT ON;
    UPDATE dbo.Table1 SET LastUpdated = GETDATE()
END
GO

But because I don't have a WHERE Clause, ALL records get updated.

QUESTION:
Where would I get the value of the ID of the updated record on a UPDATE Trigger?

Would the fact that I'm updating a field of the table inside the Trigger, re-call a new Trigger event (and so on) ?

like image 874
SF Developer Avatar asked Mar 01 '12 19:03

SF Developer


People also ask

How do you update a trigger in SQL?

Using SQL Server Management Studio Expand the database that you want, expand Tables, and then expand the table that contains the trigger that you want to modify. Expand Triggers, right-click the trigger to modify, and then click Modify. Modify the trigger, and then click Execute.

How do I create a trigger update?

In this syntax: First, specify the name of the trigger that you want to create in the CREATE TRIGGER clause. Second, use AFTER UPDATE clause to specify the time to invoke the trigger. Third, specify the name of the table to which the trigger belongs after the ON keyword.

How update trigger works in SQL Server?

A trigger is a special type of stored procedure that automatically runs when an event occurs in the database server. DML triggers run when a user tries to modify data through a data manipulation language (DML) event. DML events are INSERT, UPDATE, or DELETE statements on a table or view.

Can we update a trigger?

If specified, it allows you to re-create the trigger is it already exists so that you can change the trigger definition without issuing a DROP TRIGGER statement. The name of the trigger to create. It indicates that the trigger will fire after the UPDATE operation is executed.


2 Answers

From 'INSERTED', table INSERTED is common to both the INSERT, UPDATE trigger.

CREATE TRIGGER dbo.Table1_Updated
ON dbo.Table1
FOR INSERT, UPDATE /* Fire this trigger when a row is INSERTed or UPDATEd */
AS BEGIN
  UPDATE dbo.Table1 SET dbo.Table1.LastUpdated = GETDATE()
  FROM INSERTED
  WHERE inserted.id=Table1.id
END
like image 194
dani herrera Avatar answered Oct 11 '22 00:10

dani herrera


Update table1
set LastUpdated = getdate()
from inserted i, table1 a
where i.pk1 = a.pk1
like image 23
Alex Polkhovsky Avatar answered Oct 11 '22 00:10

Alex Polkhovsky