目标:
我想知道一个表最近每天更新一次。
是否有一种更有效的方法来查询数据库中每个表的max(insert_stamp),而无需执行以下操作:
select 't1' as table_name, max(insert_stamp) as latest_update
from t1
union all
select 't2' as table_name, max(insert_stamp)
from t2
...
或类似的东西:
use products
go
SELECT st.name as table_name, ... (column name with insert_stamp)
from sys.tables st
where st.name not like ('staging%')
group by st.name
order by 1
答案 0 :(得分:1)
我真的很讨厌这个,但这是我刚刚快速输入的内容。
但是,这将为您提供所需的东西。
SELECT
name
, ROW_NUMBER() OVER (Order by name asc) as ROWID
INTO #tmp
FROM sys.Objects WHERE type='U'
declare @count int, @rowMax int, @date datetime, @sql varchar(max);
set @count = 1
set @rowMax =(SELECT Max(ROWID) FROM #tmp);
CREATE TABLE #dates
(
name varchar(255)
, timestamp datetime
)
WHILE @count <= @RowMax
BEGIN
set @sql = 'SELECT MAX(insert_stamp) FROM '+(SELECT Name FROM #tmp WHERE ROWID=@count)+';'
exec sp_executesql @sql, N'@x datetime out', @date out
INSERT INTO #dates SELECT (SELECT Name FROM #tmp WHERE ROWID=@count), @date
set @count=@count+1
END
SELECT * FROM #dates