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

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

Related

SQL Server trigger, insert shortened version of string

I want to make a trigger that, when I insert a string into column A, a shorter version (max 117 chars) gets inserted into column B, both in the same table.
How would I do this using SQL Server 2014?
In SQL Server 2014, you don't need a trigger or even a second column storing the data. Just use a computed column:
alter table t add b as (left(a, 117))
Triggers are not advisable but you could use this
CREATE TRIGGER tx_Shorten
ON [YourTable]
AFTER Update, Insert
AS
BEGIN
IF (SELECT [YourColumn2] FROM inserted) <> (SELECT [YourColumn2] FROM
deleted)
BEGIN
UPDATE [YourTable]
SET [YourColumn2] = (SELECT LEFT([YourColumn], 117))
FROM [YourTable]
END
END

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.

timestamp, rowversion and datetime - I need a mark when a row is inserted or updated

I have the following requirement:
I have a table with 1 unique auto-incremental Int ID and data columns.
I need the following:
Every time a row is inserted into that table, a column at the right end of the table must hold the full datetime of that insert.
Also, if a row is updated I need that column that holds the full datetime of the insert of that row into the table, to be updated to hold the update time for that row.
Now the obvious and very straightforward way to do this is:
you create your table:
create table My_Test_Table
(my_id int identity not null,
my_data nvarchar(max));
you alter your table adding the datetime column and a Default constraint on it:
ALTER TABLE My_Test_Table
ADD [timestamp] datetime;
ALTER TABLE My_Test_Table
ADD CONSTRAINT DF_My_Test_Table_timestamp DEFAULT GETDATE() FOR [timestamp];
then you make a nice trigger for update, like so:
CREATE TRIGGER DML_Trigger_update_My_Test_Table
ON My_Test_Table
FOR UPDATE
AS
IF ##ROWCOUNT <> 0
BEGIN
IF EXISTS (SELECT * FROM INSERTED) AND EXISTS (SELECT * FROM DELETED)
BEGIN
UPDATE My_Test_Table
SET [timestamp] = GETDATE()
FROM INSERTED
WHERE My_Test_Table.my_id = INSERTED.my_id;
END
END
Now the tricky part is:
I want, for reasons that are beyond scope here, to implement this exact thing as above but without a Trigger!
Is it possible?
I do not want to use the SQL type timestamp or rowversion, this won't work for me, I need the date, time down to the milliseconds to be clearly stored in that column.
Any ideas would be much appreciated.
You don't need a trigger
You can use the DEFAULT keyword as the source value in the UPDATE statement to use, well, the DEFAULT constraint defined on that column
UPDATE
MyTable
SET
foo = ...,
bar = ...,
ChangedDateTime = DEFAULT
WHERE
...;
I wouldn't use a column called timestamp because this has meaning on SQL Server, as a synonym for rowversion. For SQL Server 2008+ use datetime2(3) to accurately record milliseconds. The "old" datetime is accurate to a rounded 3.33 milliseconds only

sql - Update Trigger to populate a ModifyDate field

I'm looking for an example of a good update trigger to update the ModifyDate field of a table.
It would be nice to handle the case where an update command updated more than one record in the table.
Is there a good template or tutorial for this?
Here's a cut and paste (and rename, to protect the innocent) of one I wrote quite some time ago (aka it works):
CREATE TRIGGER dbo.TR_iu_MyTable__LastUpdated
on dbo.MyTable
after insert, update
AS
SET NOCOUNT on
UPDATE dbo.MyTable
set LastUpdated = getdate()
where MyTableId in (select MyTableId from inserted)
UPDATE {tablename}
SET ModifyDate = GETDATE()
FROM inserted
WHERE {tablename}.{primarykey} = inserted.{primarykey}
Placed in a trigger tagged for INSERT and UPDATE actions will address your problem.
You could also do something similar for a CreateDate
UPDATE {tablename}
SET CreateDate = GETDATE()
FROM inserted
WHERE {tablename}.{primarykey} = inserted.{primarykey}
placed in a trigger tagged for INSERT action only.