以下答案(对所有数据库中的所有表执行“sp_spaceused”)对sp_spaceused
所有数据库中的所有表执行解决方案。
相反,我只能对所有数据库执行它吗?
我可以使用以下脚本查看所有数据库的结果,但如果可能的话,我想在单个 Excel 表中查看结果,如链接的答案:
DECLARE @DatabaseName NVARCHAR(255)
DECLARE @SqlQuery NVARCHAR(MAX)
-- Declare a cursor to loop through all databases
DECLARE database_cursor CURSOR FOR
SELECT name
FROM sys.databases
WHERE state_desc = 'ONLINE' -- Filter out offline databases if needed
-- Open the cursor
OPEN database_cursor
-- Fetch the first database name from the cursor
FETCH NEXT FROM database_cursor INTO @DatabaseName
-- Start looping through all databases
WHILE @@FETCH_STATUS = 0
BEGIN
-- Build the dynamic SQL query to switch database context and execute the query
SET @SqlQuery = 'USE [' + @DatabaseName + ']; EXEC sp_spaceused @oneresultset = 1'
-- Execute the dynamic SQL query
EXEC sp_executesql @SqlQuery
-- Fetch the next database name from the cursor
FETCH NEXT FROM database_cursor INTO @DatabaseName
END
-- Close and deallocate the cursor
CLOSE database_cursor
DEALLOCATE database_cursor
示例 excel-view 输出,我可以轻松复制所有行并将其作为整体粘贴到 excel 文件中:
您可以使用, 和分组构建一个巨大的动态
UNION ALL
查询,然后执行它。sys.dm_db_partition_stats
如果您还想通过数据库进行聚合,那么您可以完成以下操作:
如果您只想按数据库聚合,那么您可以显着简化:
只需执行程序即可。默认情况下,它仅针对您连接到的数据库执行。
链接问题中的示例是使用该命令
sp_msforeachdb
执行更复杂的任务,列出每个数据库使用的空间。