SQL SERVER – Adding Column Defaulting to Current Datetime in Table

Presenting a technical session is a greatest experience one can have and I enjoy doing the same. While I write this blog post, I am presenting at Great Indian Developer Summit in India. The event is a grand success and I am having a great time at this event. One of the questions which I often receive is how do one can add the column to existing table which will be auto-populated with the current datetime when the original row is inserted. There is indeed a simple solution to achieve this goal. One has to just create table with default value as a current datetime.

In following example we will first create a sample table and later we will add a column which will be defaulted to the current date time when any new record is inserted. The only drawback of this method is that if there is any existing row in your table it will be automatically have the current date time when the column is created. Honestly I do not see any solution to this issue as this is related to design of the database. If you know what was the datetime when rows were created you can update those rows with those value otherwise, just have any values stored there.

Let us see our solution. Let us first create a table which does not have column with current datetime. In our case we will assume that there are only two rows in the table.

USE tempdb
GO
-- Create Table
CREATE TABLE TestTable (ID INT, Col1 VARCHAR(100));
-- Insert Values
INSERT INTO TestTable (ID, Col1)
SELECT 1, 'First'
UNION ALL
SELECT 2, 'Second';
-- Select from table
SELECT *
FROM TestTable
GO

Now let us add a column to this table with default value as a current datetime. You will notice that the two rows which are inserted into the table have current datetime.

-- Add Column with Default Current Date Time
ALTER TABLE TestTable
ADD DateInserted DATETIME NOT NULL DEFAULT (GETDATE());
-- Select from table
SELECT *
FROM TestTable
GO

As a third step let us enter the a new row. Make sure that you do not insert any value in the newly created column where you have default value as a current date time.

-- Now Insert New Rows
INSERT INTO TestTable (ID, Col1)
SELECT 3, 'Third';
INSERT INTO TestTable (ID, Col1)
SELECT 4, 'Fourth';
GO
-- Select from table
SELECT *
FROM TestTable
GO

You will notice in the result set that the new column will contain current date time of the row created. This way you can get the value when the row was created.

Now you can clean up the resultset.

-- Clean up
DROP TABLE TestTable
GO

Here is the question back to you – “It is simple to create a column where we have default daytime value to know when the row was created. Is there any way to know when the row was updated without explicitly updating any column with datetime?”

Click to Download Scripts

Reference: Pinal Dave (http://blog.sqlauthority.com)

About these ads

11 thoughts on “SQL SERVER – Adding Column Defaulting to Current Datetime in Table

  1. Is there any way to know when the row was updated without explicitly updating any column with datetime?

    This is intresting question,
    we can use rowversion to track changes & maintain integrity,
    but I think we need explicitly update to maintain modified date.

    Like

  2. might want to mention GETUTCDATE() as the default , working across time zones working with utc date times can help with a lot of issues that come up

    Like

    • Getdate() is inherited from Sybase. CURRENT_TIMESTAMP is ANSI compliant. According to BOL, getDate () and CURRENT_TIMESTAMP performs exactly the same.

      Like

  3. How to get current field value as default depending on other field for ex if primary key value id=3 then prodno =prod-3

    Like

  4. How to get current field value as default depending on other field for ex if primary key value id=3 then prodno =prod-3 value should automatic generate and should be inserted on insert operation

    Like

    • Hi Utkarsh,

      you have to use triggers or make it a calculated attribute. If you want to index the attribute add the PERSISTED property to the attribute

      e.g.
      ALTER TABLE dbo.yourtable
      ADD [CalcAtt] AS [Id – 3] PERISTED;

      Like

  5. how to write to get createdby or modifiedby column autofilled to get the current user logged in i.e. who ever runs the insert query

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s