Sql-Server-2017

SQL Server - 如何知道哪些表已使用,哪些未使用?

  • February 4, 2020

我有一個包含 225 個表的數據庫

找出/記錄哪些表使用了哪些表的最佳方法是什麼?

我希望看到類似於下面的內容:

Table 1 - select 2222 times, insert 0 times, update 3 times, delete 0 times  
Table 2 - select 1 times, insert 50 times, update 0 times, delete 5 times

或採用以下格式:

Table 1 - select 2222  
Table 1 - update 0  
Table 2 - select 1  
Table 2 - insert 50  
Table 2 - delete 5
   SELECT t.name AS [TableName],
      fi.page_count AS [Pages],
      fi.record_count AS [Rows],
      CAST(fi.avg_record_size_in_bytes AS int) AS [AverageRecordBytes],
      CAST(fi.avg_fragmentation_in_percent AS int) AS [AverageFragmentationPercent],
      SUM(iop.leaf_insert_count) AS [Inserts],
      SUM(iop.leaf_delete_count) AS [Deletes],
      SUM(iop.leaf_update_count) AS [Updates],
      SUM(iop.row_lock_count) AS [RowLocks],
      SUM(iop.page_lock_count) AS [PageLocks]
 FROM sys.dm_db_index_operational_stats(DB_ID(),NULL,NULL,NULL) AS iop
 JOIN sys.indexes AS i ON iop.index_id = i.index_id AND
                          iop.object_id = i.object_id
 JOIN sys.tables AS t ON i.object_id = t.object_id AND
                         i.type_desc IN ('CLUSTERED', 'HEAP')
 JOIN sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED') AS fi ON fi.object_id=CAST(t.object_id AS int) AND
                                                                                    fi.index_id=CAST(i.index_id AS int)
 GROUP BY t.name, fi.page_count, fi.record_count, fi.avg_record_size_in_bytes, fi.avg_fragmentation_in_percent
 ORDER BY [RowLocks] desc

備註: sys.dm_db_index_operational_stats

(如何重置元數據記憶體中的計數器

sys.dm_db_index_operational_stats 返回的數據只有在表示堆或索引的元數據記憶體對象可用時才存在。這些數據既不是持久的,也不是事務一致的。這意味著您不能使用這些計數器來確定索引是否已被使用,或者索引最後一次使用的時間。有關這方面的資訊,請參閱 sys.dm_db_index_usage_stats。

每當將堆或索引的元數據帶入元數據記憶體並累積統計資訊時,每列的值都設置為零,直到從元數據記憶體中刪除記憶體對象。因此,活動堆或索引很可能總是在記憶體中具有其元數據,並且累積計數可能反映自上次啟動 SQL Server 實例以來的活動。不太活躍的堆或索引的元數據將在使用時移入和移出記憶體。因此,它可能有也可能沒有可用的值。刪除索引將導致相應的統計資訊從記憶體中刪除,並且不再由函式報告。針對索引的其他 DDL 操作可能會導致統計資訊的值重置為零。)

引用自:https://dba.stackexchange.com/questions/258864