update the value of a column every time an update is made to the row - tsql

I am using SQL Server 2012. I need to track all the rows that were updates (as part of any action) made on a table.
I thought to add a new column (Column Name: "LastUpdated" of type Datetime.) to the table that I want to track. I would like to update the LastUpdated value every time an update is made to that row. Is there a specific way to acheive this task?

You could create a trigger. Like this:
CREATE TRIGGER dbo.Table1_Updated
ON dbo.Table1
FOR UPDATE /* Fire this trigger when a row is UPDATEd */
AS BEGIN
UPDATE dbo.Table1 SET dbo.Table1.LastUpdated = GETDATE()
FROM INSERTED
WHERE inserted.id=Table1.id
END
However, this trigger will not store WHAT was updated. Also keep in mind that if two people update it, you will only have the date of the most recent update (not all updates).
To keep a history on all changes, you might want to create an audit table (nearly identical structure to your existing table) and use a trigger to copy the pre-update data into the audit table.
This SO article talks about a solid approach: Using table auditing in order to have "snapshots" of table

You would want to look into creating a trigger to fire on update
Create TRIGGER Trigger_Name ON Table_Name
FOR update
AS
BEGIN
// update lastupdated column of updated record with current date and or time
END
Alliteratively you could just pass the new value for lastupdated when updating the other fields

We have implemented a system similar to the following:
Add a new column to your table LastUpdatedDate with a datatype of datetime
If needed, add another column with LastUpdatedBy with a datatype of varchar(100) or whatever length you need
This will store both the date/time and who performed the update.
Then when you update the row in the table, you will include those two columns in your update statement similar to this:
update yourtable
set yourCol = 'newValue',
LastUpdatedDate = getdate(),
LastUpdatedBy = 'yourUserIdentifier'

Related

Created date, last modified date fields in postgress

In PostgreSQL, is there a way to add columns that will automatically record the creation date and latest updated date of a row?
for table creation date look to event triggers
for insertion look into DEFAULT value for timestamptz column (works only if you don't explicitly define value)
for last modification, use trigger FOR EACH ROW before DELETE/UPDATE
The idea - Robust way of adding created and modified fields for data we add to database through db triggers
Update modified_by and modeified_on or modified_at for every db transaction.
Pick created_on and created_by or created_at from modified details whenever you insert a row into tables.
For trigger function, check this repo https://github.com/charan4ks/created_fields.git

"ON UPDATE" equivalent for Amazon Redshift

I want a create a table that has a column updated_date that is updated to SYSDATE every time any field in that row is updated. How should I do this in Redshift?
You should be creating table definition like below, that will make sure whenever you insert the record, it populates sysdate.
create table test(
id integer not null,
update_at timestamp DEFAULT SYSDATE);
Every time field update?
Remember, Redshift is DW solution, not a simple database, hence updates should be avoided or minimized.
UPDATE= DELETE + INSERT
Ideally instead of updating any record, you should be deleting and inserting it, so takes care of update_at population while updating which is eventually, DELETE+INSERT.
Also, most of use ETLs, you may using stg_sales table for populating you date, then also, above solution works, where you could do something like below.
DELETE from SALES where id in (select Id from stg_sales);
INSERT INTO SALES select id from stg_sales;
Hope this answers your question.
Redshift doesn't support UPSERTs, so you should load your data to a temporary/staging table first and check for IDs in the main tables, which also exist in the staging table (i.e. which need to be updated).
Delete those records, and INSERT the data from the staging table, which will have the new updated_date.
Also, don't forget to run VACUUM on your tables every once in a while, because your use case involves a lot of DELETEs and UPDATEs.
Refer this for additional info.

Scala Slick auto update a column when the row is updated

I want add a updated_at column for every table.
The column will update its value with current time when the row is updated.
How can I automatic update it's value to avoid writing verbose code?
Thanks
You can do that directly in the database, don't need to modify your Slick code. you can define it like this, then it will automatically update whenever any value of this row is modified:
alter table xx add column updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
(this works mysql, not sure if needs adjustment for other databases)

Using a Database Trigger to move a record

I am new to the use of Database triggers so I want to get pointed in the right direction here. I would like to make a trigger to execute on 'insert' of new Invoice or 'Update' of 'BalanceDue' of my Invoice table to take the VendorID in Invoices, Grab the Vendor row in the Vendors table and move some data from that row to another table for ShippingLabels. This is what I got so far but Im kinda at a loss for where to go from here.
CREATE TRIGGER trSetShippingLabels
ON tblInvoices
AFTER Insert, Update
AS
INSERT INTO tblShippingLabels
SELECT VendorName, VendorAddress, VendorCity, VendorState, VendorZipCode
FROM tblVendors
JOIN tblInvoices i on i.VendorID = Vendors.VendorID
You're pretty close. You just need to use the special "inserted" table within your trigger. This table is accessible within triggers (or in conjunction with the output clause), and holds all the data inserted by the last statement executed against the relevant permanent table. There is also a corresponding "deleted" table if you wanted to remove some data in a trigger.
CREATE TRIGGER trSetShippingLabels
ON tblInvoices
AFTER Insert,Update
AS
INSERT INTO tblShippingLabels
SELECT VendorName, VendorAddress, VendorCity, VendorState, VendorZipCode
FROM Vendors
JOIN Inserted i on i.VendorID = Vendors.VendorID

T-SQL Update trigger with multiple rows

Consider a trigger after update on the table A.
For every update the trigger should update all the records in table B.
Then consider this query:
UPDATE A SET X = Y
Apparently there are many rows updated. After the update the trigger takes place.
Now if the trigger would be using inserted table, and you would like to update the table B with every single row of the temporary table inserted, and in MSDN is not recommended to use cursors, how would you do that?
Thank you
I don't know what exactly you want to do in your update trigger, but you could e.g.
UPDATE dbo.B
SET someColumn = i.Anothervalue
FROM Inserted i
WHERE b.Criteria = i.Criteria
or something else - you need to tell us a bit more about what it is you want to do with table B! But it's definitely possible to update, insert into or other things, without using a cursor and handling multiple rows from the Inserted table.
I will assume that table A is related to table B via a key (have to assume, as you posted no details).
If that is the case, you can use either sub-queries or joins with inserted to select the rows that need changing on table B.
UPDATE tableB B
SET B.colx = someValue
WHERE B.id IN
(
SELECT b_id
FROM INSERTED
)