10

How can you query SQL Server for the creation date for a SQL Server 2005 table column?

I tried the sp_columns [tablename] to get that information, but the creation date wasn't included in this stored procedure.

How can this be done?

1

7 Answers 7

8

There's this system table named sys.Columns that you can get columns information from it. if you want to see columns of a particular table you can do as follows:

SELECT col.* from sys.objects obj 
inner join sys.columns col 
on obj.object_Id=col.object_Id 
and obj.Name=@tableName

Or you can get table information like this:

SELECT * FROM sys.objects WHERE Name=@tableName

but I couldn't find any information on creation date of a column.

Updated: This might help.

6
  • why not use "sys.tables" for the table information?? Why always go to sys.objects ???
    – marc_s
    Sep 15, 2009 at 7:24
  • I don't know! It's an old habit I guess :) Sep 15, 2009 at 8:13
  • 4
    +1 - column creation date does not appear to be available and for link provided
    – AdaTheDev
    Sep 23, 2009 at 10:19
  • @marc_s The question is when a particular column was created, not when the table was created.
    – Stewart
    Nov 23, 2018 at 16:53
  • 1
    @marc_s Oh yes, so you meant using sys.tables where the queries in the answer use sys.objects. Makes more sense now.
    – Stewart
    Nov 28, 2018 at 9:56
8

SQL Server does not keep track of specific changes to tables. If you want or need this level of detail, you need to create a DDL Trigger (introduced in SQL Server 2005) that can trap certain specific events or even classes of events, and log those changes to a history table that you create.

DDL Triggers are "after" triggers; there is no "instead of" option. However, if you want to disallow an action, you can just issue a ROLLBACK and that will cancel what happened.

The MSDN page for DDL Triggers has a lot of good information regarding how to trap either specific events (i.e. ALTER TABLE) and using the EVENTDATA function, which returns XML, to get the specifics of what event fired the trigger, including the exact SQL query that was executed. In fact, the MSDN page for Use the EVENTDATA Function even has simple examples of creating a DDL trigger to capture ALTER TABLE statements (in the " ALTER TABLE and ALTER DATABASE Events" section) and creating a DDL trigger to capture the events to a log table (in the "Example" section). Since all ALTER TABLE commands will fire this trigger, you need to parse out which ones are specific to what you are looking for. And, maybe now that you know that this is an option, capturing more than just adding columns is desired (i.e. dropping columns, changing the datatype and/or NULLability, etc).

It should be noted that you can create a DLL trigger ON ALL SERVER for database-scoped events such as ALTER_TABLE.

If you want to see the structure of the XML for any event or event class, go to:

http://schemas.microsoft.com/sqlserver/2006/11/eventdata/

and click on the "Current version:" link. If you want to see a specific event or event class, just do a search (usually Control-F in the browser) on the event name that would be used in the trigger's "FOR" clause (including the underscore). The following is the schema for the ALTER_TABLE event:

<xs:complexType name="EVENT_INSTANCE_ALTER_TABLE">
<xs:sequence>
<!--  Basic Envelope  -->
<xs:element name="EventType" type="SSWNAMEType"/>
<xs:element name="PostTime" type="xs:string"/>
<xs:element name="SPID" type="xs:int"/>
<!--  Server Scoped DDL  -->
<xs:element name="ServerName" type="PathType"/>
<xs:element name="LoginName" type="SSWNAMEType"/>
<!--  DB Scoped DDL  -->
<xs:element name="UserName" type="SSWNAMEType"/>
<!--  Main Body  -->
<xs:element name="DatabaseName" type="SSWNAMEType"/>
<xs:element name="SchemaName" type="SSWNAMEType"/>
<xs:element name="ObjectName" type="SSWNAMEType"/>
<xs:element name="ObjectType" type="SSWNAMEType"/>
<xs:element name="Parameters" type="EventTag_Parameters" minOccurs="0"/>
<xs:element name="AlterTableActionList" type="AlterTableActionListType" minOccurs="0"/>
<xs:element name="TSQLCommand" type="EventTag_TSQLCommand"/>
</xs:sequence>
</xs:complexType>

Here is a very simple test to see how this works and what the resulting EventData XML looks like:

IF (EXISTS(
   SELECT *
   FROM   sys.server_triggers sst
   WHERE  sst.name = N'CaptureAlterTable'
   ))
BEGIN
  DROP TRIGGER CaptureAlterTable ON ALL SERVER;
END;
GO

CREATE TRIGGER CaptureAlterTable
ON ALL SERVER -- capture events for all databases
FOR ALTER_TABLE -- only capture ALTER TABLE events
AS
  PRINT CONVERT(NVARCHAR(MAX), EVENTDATA()); -- Display in "Messages" tab in SSMS
GO

First we create a simple, real table in tempdb (these events are not captured for temp tables):

USE [tempdb];
CREATE TABLE dbo.MyAlterTest (Col2 INT NULL);

Next we add a column. We do this from a different database to make sure that the XML captures the database where the object exists instead the current database. Please note the casing of the words alTeR Table tempDB.dbo.MyALTERTest ... DATEcreated to compare with what is in the XML.

USE [master];
alTeR Table tempDB.dbo.MyALTERTest ADD DATEcreated DATETIME NOT NULL;

You should see the following in the "Messages" tab (comments added by me):

<EVENT_INSTANCE>
  <EventType>ALTER_TABLE</EventType>
  <PostTime>2014-12-15T10:53:04.523</PostTime>
  <SPID>55</SPID>
  <ServerName>_{server_name}_</ServerName>
  <LoginName>_{login_name}_</LoginName>
  <UserName>dbo</UserName>
  <DatabaseName>tempdb</DatabaseName> <!-- casing is based on database definition -->
  <SchemaName>dbo</SchemaName>
  <ObjectName>MyAlterTest</ObjectName> <!-- casing is based on object definition -->
  <ObjectType>TABLE</ObjectType>
  <AlterTableActionList>
    <Create>
      <Columns>
        <Name>DATEcreated</Name> <!-- casing is taken from executed query -->
      </Columns>
    </Create>
  </AlterTableActionList>
  <TSQLCommand>
    <SetOptions ANSI_NULLS="ON" ANSI_NULL_DEFAULT="ON" ANSI_PADDING="ON" QUOTED_IDENTIFIER="ON" ENCRYPTED="FALSE"/>
    <CommandText>alTeR Table tempDB.dbo.MyALTERTest ADD DATEcreated DATETIME NOT NULL;&#x0D;
</CommandText>
  </TSQLCommand>
</EVENT_INSTANCE>

It would have been nice if the per-column details (i.e. NULL / NOT NULL, datatype, etc) were captured instead of just the name, but if need be, those can be parsed out of the CommandText element.

2

Bit late to the party but found something that helped for me. If you can say the column is the last change to the table then sys.tables(modify_date) is workable.

1

I think there is no way of getting modification or creation date of individual columns per se. The queries given in this and this answer returns the dates related to Table containing the column not the column. Because sys.columns table have same id for all the columns in the table. You can verify this by running this query

select col.object_id, col.name, col.column_id
from sys.columns col
where col.object_id = 
(select o.object_id from sys.objects o where o.Name = @tableName)
1
  • 1
    or: where col.object_id = OBJECT_ID('table_name') - seems easier to me
    – marc_s
    Sep 15, 2009 at 7:24
1
SELECT so.name,so.modify_date
FROM sys.objects as so
    INNER JOIN INFORMATION_SCHEMA.TABLES as ist
ON ist.TABLE_NAME=so.name where ist.TABLE_TYPE='BASE TABLE' AND
 TABLE_CATALOG='dbName' order by so.modify_date desc;
0

I don't think this information is available unless you have something that can browse the transaction logs, like Log Explorer. It's not a tsql thing.

0

I had an issue where I had to replicate tables to another server and I wanted to do this exact thing but there was nothing in the sys tables that showed me when a column was added or changed. Since I know my current table has the correct columns I did the following in a do loop:

declare @CurrentTableCount int = 0,
        @SchemaCheckTableCount = 0

  select top 1 * into TableNameSchemaCheck from OpenQuery
 (Database, 'select * from TableName where 1 = 2')

 select @CurrentTableCount = (select count(1) from sys.syscolumns c
                                inner join sys.sysobjects o on c.id = o.id
                                  where o.xtype = 'U'
                                    and o.name = 'TableName')

 select @SchemaCheckTableCount = (select count(1) from sys.syscolumns c
                                   inner join sys.sysobjects o on c.id = o.id
                                   where o.xtype = 'U'
                                     and o.name = 'TableNameSchemaCheck')

    if @CurrentTableCount <> @SchemaCheckTableCount
     begin

      insert into SchemaCheckLog
       values ('CompanyContext', getdate(), 'Schema for TableName table has changed.', 0)

       end

     drop table TableNameSchemaCheck

 end

I built a procedure that emails me results in that table and then I know the schema of the source table has changed and I need to change it in the target.

You could then expand on this and find the column names that are different but my use case doesn't require that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.