有没有办法找出数据最后输入表格的时间?我正试图在我的数据库中找到过时的表,并想知道是否有一个我可以运行的简单脚本?
答案 0 :(得分:8)
您可以尝试检查查询sys.dm_db_index_usage_stats动态管理视图的结果,如下所示:
SELECT *
FROM sys.dm_db_index_usage_stats
WHERE [database_id] = DB_ID()
AND [object_id] = OBJECT_ID('TableName')
这将返回表格上索引的last_user_seek,扫描和更新日期等内容。
但是,请注意,重新启动服务器时会重置动态管理视图的统计信息。服务器运行的时间越长,如果记录显示没有活动,您就越有信心。
我个人也会检查所有源代码以检查对相关表的引用,并搜索所有sprocs / UDF以获取引用(您可以使用SQL Search from Red Gate执行此操作 - 它是免费的)
答案 1 :(得分:1)
如果有人在数据库中查找所有未使用的表(标题的请求多于问题正文),this guy有一个很好的查询来引入数据库中所有未更改的表。在这种情况下,“未更改”是sys.dm_db_index_usage_stats
中没有条目的任何表(再次,与AdaTheDev的答案一样,仅在上次sql server重新启动后)。
SELECT OBJECTNAME = Object_name(I.object_id),
INDEXNAME = I.name,
I.index_id
FROM sys.indexes AS I
INNER JOIN sys.objects AS O
ON I.object_id = O.object_id
WHERE Objectproperty(O.object_id, 'IsUserTable') = 1
AND I.index_id NOT IN (SELECT S.index_id
FROM sys.dm_db_index_usage_stats AS S
WHERE S.object_id = I.object_id
AND I.index_id = S.index_id
AND database_id = Db_id(Db_name()))
ORDER BY objectname,
I.index_id,
indexname ASC
答案 2 :(得分:1)
上次查询:
-- Create CTE for the unused tables, which are the tables from the sys.all_objects and
-- not in the sys.dm_db_index_usage_stats table
; with UnUsedTables (TableName , TotalRowCount, CreatedDate , LastModifiedDate )
AS (
SELECT DBTable.name AS TableName
,PS.row_count AS TotalRowCount
,DBTable.create_date AS CreatedDate
,DBTable.modify_date AS LastModifiedDate
FROM sys.all_objects DBTable
JOIN sys.dm_db_partition_stats PS ON OBJECT_NAME(PS.object_id)=DBTable.name
WHERE DBTable.type ='U'
AND NOT EXISTS (SELECT OBJECT_ID
FROM sys.dm_db_index_usage_stats
WHERE OBJECT_ID = DBTable.object_id )
)
-- Select data from the CTE
SELECT TableName , TotalRowCount, CreatedDate , LastModifiedDate
FROM UnUsedTables
ORDER BY TotalRowCount ASC
上次更新时间:
With Unused_Tables (Table_Name, Row_Count, Created_Date, Last_Modified_Date,
Last_User_Lookup, Last_User_Scan, Last_User_Seek, Last_User_Update)
AS (
SELECT AO.name AS Table_Name
,PS.row_count AS Row_Count
,AO.create_date AS Created_Date
,AO.modify_date AS Last_Modified_Date
,ius.last_user_lookup AS Last_User_Lookup
,ius.last_user_scan AS Last_User_Scan
,ius.last_user_seek AS Last_User_Seek
,ius.last_user_update AS Last_User_Update
FROM sys.all_objects AO
JOIN sys.dm_db_partition_stats PS ON OBJECT_NAME(PS.object_id)=AO.name
LEFT JOIN sys.dm_db_index_usage_stats ius ON OBJECT_NAME(ius.object_id)=AO.name
WHERE AO.type ='U'
)
SELECT * FROM Unused_Tables
Where ISNULL(Last_User_Lookup,'1900-01-01')<DATEADD(month, -1, GETDATE()) AND
ISNULL(Last_User_Scan,'1900-01-01')<DATEADD(month, -1, GETDATE()) AND
ISNULL(Last_User_Seek,'1900-01-01')<DATEADD(month, -1, GETDATE()) AND
ISNULL(Last_User_Update,'1900-01-01')<DATEADD(month, -1, GETDATE())
ORDER BY Row_Count DESC
答案 3 :(得分:0)
如果这对您的应用程序和/或公司很重要,并且表格设计正确,那么每个表都应该有一个名为“LastModifiedTime”的列。您可以查询此表以确定哪些表已过时。