declare @TablesCnt int, @Loop int, @Schema sysname,
@Table sysname, @SQL nvarchar(max)
if object_id('tempdb..#ListOfTables') IS NOT NULL
drop table #ListOfTables
select identity(int,1,1) as Row, table_schema, Table_Name into #ListOfTables from Information_Schema.Columns C1 where
Column_Name LIKE '%ID' and
exists (select 1 from Information_Schema.Columns C2
where C1.Table_Name = C2.Table_Name and
C2.Column_Name = 'ModifiedDate') order by Table_Name
set @TablesCnt = @@ROWCOUNT
--select * from #ListOfTables
if object_id('Result','U') IS not NULL
drop table Result
create table Result (SchemaName sysname, TableName Sysname, LatestDate datetime)
set @Loop = 1
while @Loop <=@TablesCnt
begin
select @Table = Table_Name, @Schema = Table_schema from #ListOfTables where Row = @Loop
set @Loop = @Loop + 1
set @SQL = 'select ' + QUOTENAME(@schema,'''') + ' as [Schema], ' +
quotename(@Table,'''') + ' as Table_Name, max(ModifiedDate) as LastDate from ' + quotename(@Schema) + '.' + quotename(@Table)
insert into Result execute (@SQL)
--execute (@SQL)
end
select * from Result
go
-- Test query
declare @SQL varchar(max)
select @SQL = stuff((select top (50) char(13) + char(10) + 'UNION ALL ' +
'SELECT ' + quotename(table_schema,'''') + ' as [Schema], ' + quotename(Table_Name,'''') +
' as [TableName], max(ModifiedDate) as [LastDate] from ' +
QUOTENAME(Table_SCHEMA) + '.' +
quotename(Table_Name) from (select Table_Name, TABLE_SCHEMA
from Information_Schema.Columns C1 where
Column_Name Like '%ID' and
exists (select 1 from Information_Schema.Columns C2
where C1.Table_Name = C2.Table_Name and
C2.Column_Name = 'ModifiedDate') group by TABLE_NAME, TABLE_SCHEMA) X order by Table_Name
for XML PATH(''),type).value('.','varchar(max)'),1,12,'')
--print @SQL
execute (@SQL)