SQL Server Update / Modified Date Field - sql

I am using the following trigger to track the last modified date in a table:
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM Inserted)
It says "AFTER UPDATE", but even when I insert a row, it sets the ModDate column to the same as the entry date. How can I stop this from happening? I only want it to change when I make a chance to a row, not when a new row is added (it should stay NULL in this case).
Thanks!

CREATE TRIGGER trg_update_my_table on my_table
FOR UPDATE AS
BEGIN
UPDATE my_table
SET modified_on=getdate()
FROM my_table INNER JOIN deleted d
on my_table.id = d.id
END
GO
OR you can change definition of or existing trigger to
CREATE TRIGGER trg_UpdateTimeEntry
ON dbo.TimeEntry
AFTER UPDATE
AS
UPDATE dbo.TimeEntry
SET ModDate = GETDATE()
WHERE ID IN (SELECT DISTINCT ID FROM deleted)
inserted table will have all the newly inserted records and new values for any updated records, deleted table will have only old values of the records that were updated.

Related

Create a trigger that updates a column in a table when a different column in the same table is updated - SQL

How to create a trigger that updates a column in a table when a different column in the same table is updated.
So far I have done the following which works when any new data is created. Its able to copy data from "Purchase Requisition" to "PO_Number" however when data has been modified in "Purchase Requisition" , no changes is made to "PO_Number" and the value becomes NULL. Any kind help will be seriously appreciated.
ALTER TRIGGER [dbo].[PO_Number_Trigger]
ON [dbo].[TheCat2]
AFTER INSERT
AS BEGIN
UPDATE dbo.TheCat2 SET PO_Number=(select Purchase_Requisition from inserted) where DocNo= (Select DocNo from inserted);
END
You need to add 'UPDATE' as well as insert to the trigger, otherwise it will only execute on new data, not updated data. Also added 'top 1' to the select statements from the inserted table to allow this to be 'safe' on batch updates, however it will only update 1 record.
ALTER TRIGGER [dbo].[PO_Number_Trigger]
ON [dbo].[TheCat2]
AFTER INSERT, UPDATE
AS BEGIN
UPDATE dbo.TheCat2 SET PO_Number=(select top 1 Purchase_Requisition from inserted) where DocNo= (Select top 1 DocNo from inserted);
END
This might do what you want:
Your trigger is altering all rows in TheCat2. Presumably, you only want to alter the new ones:
ALTER TRIGGER [dbo].[PO_Number_Trigger]
ON [dbo].[TheCat2] AFTER INSERT
AS
BEGIN
UPDATE tc
SET PO_Number = Purchase_Requisition
FROM dbo.TheCat2 tc JOIN
inserted i
on tc.DocNo = i.DocNo ;
END;
However, perhaps a computed column is sufficient for your purposes:
alter table add PO_Number as Purchase_Requisition;

How to update specific row in datecolumn to date today after update on other column using after update trigger?

How to update date Column DateMod to today's date when Column CustomerProductID is updated (not inserted) using an after update trigger in T-SQL?
Some background info: Table already contains list of products (key column Itemcode), once the CustomerProductID is received it changes the column for that particular row (product) from NULL to integer value. This update is the trigger to update column DateMod to todays date for the row (product).
I am using SSMS 2008 and have something like the following code which changes the whole date column, not the particular date field for the updated row:
CREATE TRIGGER trigger_name
ON Table1
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE (CustomerProductID) BEGIN
Update Table1
SET DateMod=GETDATE()
END
END
I have read some solutions using old.value and new.value or using where exists (select from inserted/updated), but how does that work? If both methods work, which one is the most beneficial in this case?
Thanks a lot!
I prefer do this as a before update trigger (a logical thing . . . doing updates in after update triggers suggests infinite loops and is not allowed in some databases). But SQL Server doesn't support that.
In any case, the right syntax is to use inserted to join back to the original table:
CREATE TRIGGER trigger_name
ON Table1
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
IF UPDATE(CustomerProductID) BEGIN
Update t1
SET DateMod = GETDATE()
FROM Table1 t1 join
Inserted i
ON Table1.PrimaryKeyColumn = i.PrimaryKeyColumn
END
END
Change the code so PrimaryKeyColumn is the right primary key column.

Create a Table that has Created Date and Update Date (Read Only)

I wonder if it is possible to create a table that has a created date and updated date every time a record is created or updated.
For example, when I insert a record into that table, the created date will auto generated in the table same with the update date.
When I modify this record, the create date won't change but the update date will change according to the date.
Many thanks
CREATE TABLE dbo.foo
(
ID INT IDENTITY(1,1),
CreatedDate DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
UpdatedDate DATETIME NULL
);
GO
CREATE TRIGGER dbo.foo_ForUpdate
ON dbo.foo
FOR UPDATE
AS
BEGIN
SET NOCOUNT ON;
UPDATE f SET UpdatedDate = CURRENT_TIMESTAMP
FROM dbo.foo AS f
INNER JOIN inserted AS i
ON f.ID = i.ID;
END
GO
You can set the default value for the column to be equal to GetDate() and this will set the Created Date to the time when the record was created. This will not work for UpdatedDate because default values will be used when the record is created. For this column you can use after update trigger. Here is a link that shows how to create one :
http://www.sqlservercurry.com/2010/09/after-update-trigger-in-sql-server.html
Trigger is a most suitable option. You can refer the sample for trigger as follows.
CREATE TRIGGER dbo.TableTriggerName
ON dbo.TableName
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
SET NOCOUNT ON;
--
-- Check if this is an INSERT, UPDATE or DELETE Action.
-- Set Action to Insert by default.
IF EXISTS(SELECT * FROM DELETED)
BEGIN
END
ELSE
IF NOT EXISTS(SELECT * FROM INSERTED) RETURN; -- Nothing updated or inserted.
...
END
Trigger Reference

Data Type that automatically stores the DateTime of the last transaction done, SQL Server 2008

I need to add a new column to an existing table, so that whenever a new row is added, or an existing row is edited, this column will be filled with the exact date and time of the transaction. I tried using TimeStamp but apparently TimeStamp it has nothing to do with Date time
It's just a binary representation of a consecutive number - it's only good for making sure a row hasn't change since it's been read. (Quoted from How to convert SQL Server's timestamp column to datetime format
Any help is highly appreciated
It sounds like you need to create a trigger to populate/update this new column. See the following: How to: Create trigger for auto update modified date with SQL Server 2008
You have to create a trigger on INSERT and UPDATE for the table and in the trigger you can use
UPDATE myTable
SET myColumn = GETDATE()
Your trigger should look somethign like
CREATE TRIGGER trigger_updateTimestamp
ON myTable
AFTER INSERT, UPDATE
AS
UPDATE myTable
SET myColumn = GETDATE()
WHERE ID = 'xyz'
try
ALTER TABLE myTable ADD CONSTRAINT [DF_myTable_myColumn] DEFAULT (getdate()) FOR [myColumn]
GO
... and a good practice is to have an extra column for edited date, and update using a trigger
CREATE TRIGGER trigger_updateMyTable
ON myTable
AFTER UPDATE
AS
IF EXISTS (SELECT * FROM INSERTED)
BEGIN
IF ΝΟΤ EXISTS (SELECT * FROM DELETED)
BEGIN
UPDATE myTable
SET myEditColumn = GETDATE()
WHERE ID IN (
SELECT
ID
FROM INSERTED
)
END
END

Trigger only modify updated/inserted row

Hi I have the following trigger.
ALTER TRIGGER [dbo].[DivisionLastModified] ON [dbo].[tb_Division]
WITH EXECUTE AS CALLER
FOR INSERT, UPDATE
AS
BEGIN
UPDATE tb_Division SET LastModified = GetDate()
END
This updates all rows however I only wish to modify the update/added row.
Is this achievable?
This is Because you update all Rows
UPDATE tb_Division SET LastModified = GetDate()
You must specify the last inserted or updated row id,
so you can specify that in Where condition some thing like this
UPDATE tb_Division SET LastModified = GetDate() where id=4
To just update LastModified on the rows that were affected by the insert or update you need to use the inserted table which is only available in triggers.
ALTER TRIGGER [dbo].[DivisionLastModified]
ON [dbo].[tb_Division]
WITH EXECUTE AS CALLER FOR INSERT, UPDATE AS
BEGIN
UPDATE tb_Division
SET LastModified = GetDate()
WHERE tb_Division.<Primary Key Column Name Here> IN (
SELECT <Primary Key Column Name Here> FROM inserted
)
END