Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a “last modified” and "created" column in a SQL Server table?

I'm design a new db schema for a SQL Server 2012 database.

Each table should get two extra columns called modified and created which should be automatically change as soon a row gets inserted or updated.

I don't know how rather the best way to get there.

I assuming that trigger are the best way to handle it.

I was trying to find examples with triggers.. but the tutorials which I found insert data in another table etc.

I assumed it's a quite common scenario but I couldn't find the answer yet.

like image 682
stevo Avatar asked Jul 26 '15 08:07

stevo


People also ask

How can I add last modified date in SQL?

Some database tables include a “last modified” column, which stores the date and time that the row was last updated. Each time the row is updated, the date is updated to reflect the date and time of that update. In SQL Server, you can use a trigger to perform this update.

How do I find the last modified column in SQL Server?

Solution. 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 do I add a column to an already created table?

The basic syntax of an ALTER TABLE command to add a New Column in an existing table is as follows. ALTER TABLE table_name ADD column_name datatype; The basic syntax of an ALTER TABLE command to DROP COLUMN in an existing table is as follows.


1 Answers

The created column is simple - just a DATETIME2(3) column with a default constraint that gets set when a new row is inserted:

Created DATETIME2(3)     CONSTRAINT DF_YourTable_Created DEFAULT (SYSDATETIME()) 

So when you insert a row into YourTable and don't specify a value for Created, it will be set to the current date & time.

The modified is a bit more work, since you'll need to write a trigger for the AFTER UPDATE case and update it - you cannot declaratively tell SQL Server to do this for you....

Modified DATETIME2(3) 

and then

CREATE TRIGGER updateModified ON dbo.YourTable AFTER UPDATE  AS    UPDATE dbo.YourTable    SET modified = SYSDATETIME()    FROM Inserted i    WHERE dbo.YourTable.PrimaryKey = i.PrimaryKey 

You need to join the Inserted pseudo table which contains all rows that were updated with your base table on your primary key for that table.

And you'll have to create this AFTER UPDATE trigger for each table that you want to have a modified column in.

like image 64
marc_s Avatar answered Oct 28 '22 01:10

marc_s