Technical Article

A quick way to find recently entered datetime entries in tables

,

Every once in a while, you find yourself with a database you have no idea who owns it or when it was last accessed. In addition to running a trace on it, you can run this script to get a quick snapshot of any datetime column entries. What it does is use syscolumns to extract each datetime column that exists, map it to it's approrpriate table, and wrap it in a dynamic SQL statement as SELECT TOP 1 <datetime column> FROM <target table> SORT BY <datetime column> DESC'

 

It's quick and dirty but gets the job done. It does rely on one MASSIVE assumption however. There has to be a datetime column that gets updated in someway (update or insert). There are some apps that use varchar(8) columns for example to capture dates such as '20100502' and this script will not catch those unfortunately. Also, if the column is not indexed and you have a very large number of rows, this could also be problematic due to the descending sort.

 

To help resolve this, I've defaulted the commands to print out the statements in case you need to verify against some of the larger tables if there is an index on that column, and cut/paste the results to query analayzer.

 

[EDIT: Fixed buggy code, included a where clause in the select from #findaccesstimes loop]

set nocount on
create table #findAccessTimes (rownum int identity(1,1), command varchar(8000))

insert into #findAccessTimes(command)
 select 'select top 1 ''' + so.name + ''' [TableName], [' + sc.name + '] from ['
 + so.name + '] (nolock) order by [' + sc.name + '] desc' from syscolumns sc
 inner join sysobjects so on so.id = sc.id
 where so.type = 'U' and sc.xtype = 61
 
declare @query varchar(8000),
 @ctr int,
 @numrows int
 
select @numrows = count(*) from #findAccessTimes
set @ctr = 1

while (@ctr <= @numrows)
begin
 select @query = command from #findAccessTimes where rownum = @ctr
 print(@query) -- Verify with this print to make sure you like the queries
 -- exec(@query) -- that are generated before actually running them.
 delete #findAccessTimes where rownum = @ctr
 set @ctr = @ctr + 1
end
go

drop table #findAccessTimes

Rate

3.5 (4)

You rated this post out of 5. Change rating

Share

Share

Rate

3.5 (4)

You rated this post out of 5. Change rating